什么是WSGI?什么是wsgiref?
WSGI(Web Server Common Interface)是专门为Python语言制定的web服务器与应用程序之间的网关接口规范,通俗的来说,只要一个服务器拥有一个实现了WSGI标准规范的模块(例如apache的mod_wsgi模块),那么任意的实现了WSGI规范的应用程序都能与它进行交互。因此,WSGI也主要分为两个程序部分:服务器部分和应用程序部分。
wsgiref则是官方给出的一个实现了WSGI标准用于演示用的简单Python内置库,它实现了一个简单的WSGI Server和WSGI Application(在simple_server模块中),主要分为五个模块:simple_server, util, headers, handlers, validate。
wsgiref源码地址:https://pypi.python.org/pypi/wsgiref
我们先不急着说明WSGI的详细标准部分,我们先看一下如何用wsgiref实现一个WSGI Server与WSGI Application交互的例子。
wsgiref简单实现WSGI Server与WSGI Application
由于simple_server中已经实现了一个简单的WSGI Server和WSGI Application,我们只要直接调用API就可以了。
from wsgiref.simple_server import make_server, demo_app
application = demo_app
server = make_server("127.0.0.1", 8000, application)
#参数分别为服务器的IP地址和端口,以及应用程序。
server.handle_request()
#处理一个request之后立即退出程序
默认的demo_app将会返回Hello World以及环境变量。
接下来我们将定义自己的应用程序。
WSGI对于应用程序有以下标准规定:
1. 应用程序必须是一个可调用的对象,因此,应用程序可以是一个函数,一个类,或者一个重载了__call__的类的实例。
2. 应用程序必须接受两个参数并且要按照位置顺序,分别是environ(环境变量),以及start_response函数(负责将响应的status code,headers写进缓冲区但不返回给客户端)。
3. 应用程序返回的结果必须是一个可迭代的对象。
遵照以上标准,实现的应用程序代码为:
def function_app(environ, start_response):
status = "200 OK"
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return ['Function : My Own Hello World!']
class class_app:
def __init__(self, environ, start_response):
self.env = environ
self.start = start_response
def __iter__(self):
status = "200 OK"
response_headers = [('Content-type', 'text/plain')]
self.start(status, response_headers)
yield "Class : My Own Hello World!"
#使用yield使应用程序返回一个可迭代对象
class instance_app:
"""
当使用类的实例作为应用程序吧,application = instance_app(), not instance_app
"""
def __call__(self, environ, start_response):
status = "200 OK"
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return ["Instantiate : My Own Hello World!"]
wsgiref.simple_server 中make_server函数剖析
想必各位对仅仅止步于一个简单的make_server函数的简单调用并不能满足,这个WSGI Server是如何实现的呢?所以接下来我们将会对wsgiref中的make_server函数的实现进行源码分析。
#wsgiref中的make_server实现
def make_server