用 Python 搭建最简单的 http 服务器

适用范围

  • 本文内容对 Python 3.6.9 适用

文件下载

python3 -m http.server 5678

WSGI

from wsgiref.simple_server import make_server

def hello_world_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)
    msg = 'Hello %s\n' % environ["REMOTE_ADDR"]
    return [msg.encode('utf8')]

with make_server('', 5678, hello_world_app) as httpd:
    print("Serving on port 5678...")
    httpd.serve_forever()

运行

  • 命令行前台运行
python3 t.py
  • 后台运行
nohup python3 -u t.py > t.log 2>&1 &
# 日志滚动,只保留最新的 1 M
nohup python3 -u t.py 2>&1 | rotatelogs -n 1 t.log 1M &

测试

$ curl 127.0.0.1:5678
Hello 127.0.0.1
本文出自 qbit snap
相关文章
相关标签/搜索