我有一个几乎完整的简单的Web应用程序,作为Python CGI脚本编写.我想把它改成使用WSGI,但我找不到文档来帮助我理解WSGI实际上是什么(一个只能重复发现带有start_response等的调用但是似乎没有太多解释这些实际上是打电话).有人能指出我一个很好的解释,加上使用WSGI的方法吗?
编辑:应该添加我已经看到这个问题,但答案仍然似乎没有告诉一个如何在直接脚本中使用WSGI(而不是在框架中).
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"]
Run Code Online (Sandbox Code Playgroud)
要运行该应用程序,您需要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)
Run Code Online (Sandbox Code Playgroud)
还有一个简单的HTTP服务器用于开发:
from wsgiref.simple_server import make_server
from my_app import app
httpd = make_server('localhost', 8000, app)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,WSGI允许您在不同的环境中重用您的应用程序 - CGI,SCGI,FastCGI,mod_wsgi,mod_python等,而无需实际重写它.
WSGI的最后一部分是中间件 - 基本上,它是一个允许您组合不同WSGI应用程序的概念.它形成一种三明治 - 从顶部(网关)到底部(通常是您的应用程序)的请求流,其间有一些中间层,可能实现数据库连接池或会话等内容.wsgiref
包含一个这样的中间件 - wsgiref.validate.validator
它检查它下面和上面的层是否符合WSGI规范的规则.
这基本上就是它.现在去使用一个框架.