用 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)

    # The returned object is going to be printed
    return [b"Hello World\n"]

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

后台运行

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 World
本文出自 walker snapshot

你可能感兴趣的:(python,http)