WSGI
即Python Web Server Gateway Interface
,也就是Python的Web服务器网关接口,定义了Python的Web应用与服务端的交互规范,类似于Java中的Servlet规范。
实现了WSGI
规范的Python模块主要有wsgiref
(Python官方的WSGI参考实现)、werkzeug.serving
(Flask用)和twisted.web
等。
from wsgiref.simple_server import make_server
make_server('localhost', 8088, lambda _, rsp: [
[
rsp("200 OK", []),
"Hello World"
][-1].encode()
]).serve_forever()
其中,传给make_server
的第三个参数即WSGI规范
状态码+状态文本
,响应头表示为二元组列表127.0.0.1 - - [19/Mar/2019 17:29:20] "GET / HTTP/1.1" 200 11
127.0.0.1 - - [19/Mar/2019 17:29:21] "GET / HTTP/1.1" 200 11
127.0.0.1 - - [19/Mar/2019 17:29:22] "GET / HTTP/1.1" 200 11
from wsgiref.simple_server import make_server
class App:
def __call__(self, _, rsp):
rsp("200 OK", [])
return ["Hello World".encode()]
make_server('localhost', 8088, App()).serve_forever()
from wsgiref.simple_server import make_server
def app(_, rsp):
rsp("200 OK", [])
return ["Hello World".encode()]
make_server('localhost', 8088, app).serve_forever()
WSGI容器,即支持运行WSGI应用的Web容器。常用的有uWSGI
和gUnicorn
以gUnicorn
(pip install gunicorn
)为例,运行方式:
gunicorn foo:app
启动foo.py
文件中名字为app
的WSGI应用
[2019-03-19 22:19:31 +0800] [59137] [INFO] Starting gunicorn 19.9.0
[2019-03-19 22:19:31 +0800] [59137] [INFO] Listening at: http://127.0.0.1:8000 (59137)
[2019-03-19 22:19:31 +0800] [59137] [INFO] Using worker: sync
[2019-03-19 22:19:31 +0800] [59140] [INFO] Booting worker with pid: 59140