WSGI 是 PEP 333(对于 Python 3 是 PEP3333),又名 Web 服务器网关接口。它包含三个部分,但您感兴趣的部分是您如何编写 WSGI 应用程序。而 WSGI app 是一个可调用对象,它接受两个参数并返回一个可迭代对象(或者是一个生成器)。
# this is my_app module
def app(environ, start_response):
# environ is dict-like object containing the WSGI environment
# refer to the PEP for details
# start_response is a callable that, well, starts the response
headers = [('Content-Type', 'text/plain; charset=utf-8')]
start_response('200 OK', headers)
return ["I'm a WSGI application.\n"]
要运行应用程序,您需要 WSGI 的另一部分,即网关。在标准库中,您会找到 wsgiref 包。它包含一个 CGI 网关:
#!/usr/bin/python
# this is a CGI script that runs a WSGI application inside CGI handler
from wsgiref.handlers import CGIHandler
from my_app import app
CGIHandler().run(app)
还有一个用于开发的简单 HTTP 服务器:
from wsgiref.simple_server import make_server
from my_app import app
httpd = make_server('localhost', 8000, app)
httpd.serve_forever()
如您所见,WSGI 允许您在不同的环境(CGI、SCGI、FastCGI、mod_wsgi、mod_python 等)中重用您的应用程序,而无需实际重写它。
WSGI 的最后一部分是中间件——基本上,它是一个允许您组合不同 WSGI 应用程序的概念。它形成了一种三明治——请求从顶部(网关)流向底部(通常是您的应用程序),中间有一些中间层,可能实现数据库连接池或会话等东西。 wsgiref 包含一个这样的中间件——wsgiref.validate.validator,它检查其上下层是否符合 WSGI 规范的规则。
基本上就是这样。现在去使用一个框架。