WSGI是什么?WSGI是 Web Server Gateway Interface的缩写,是一种规范。
如下图所示,通常服务器本身(如nginx. apache)只能应答静态网页,若要服务器回应动态网页,服务器需先把请求发给web应用程序处理,然后应用程序返回处理后的内容,最后由服务器将相应的内容应答给浏览器,在python web应用中,连接应用程序与服务器的规范就是WSGI。
在WSGI规范下,web组件被分为三类: Server, Middleware, Application。
Server: 把environ和start_response传给Application进行调用,然后遍历Application返回的Iterable,使用write函数把结果写入sys.stdin里,写入sys.stdin,也就是与Web Server(Apache/Nginx)进行通信,Web Server通过Socket获取内容后,将内容Response给浏览器。
Middleware是设计模式中的Decorator(装饰器)。是一个函数或者实现了__call__方法的对象或者实现了__init__方法的类。我们在这里统称为Callable对象。Middleware返回的对象是一个被装饰了的Application(transformedApp变量),这个transformedApp所依赖的environ和start_response可以被当前Middleware所在的上层的Server/Middleware所注入。
Application:是web应用程序,其是一个函数或者实现了__call__方法的对象,即Callable对象。其签名如下
def __call__(environ: Dict[String, Any], start_response:(String, List)->Any): Iterable[String]
environ是一个键为string,值为任意类型的字典
start_response则是一个函数。
这两个参数需要在Server调用Application时传递给Application。
下面展示由python 内置的WSGI参考库wsgiref实现的简单web程序。
# server.py # 从wsgiref模块导入: from wsgiref.simple_server import make_server def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return '<h1>Hello, web!</h1>' # 创建一个服务器,IP地址为空,端口是8000,处理函数是application: httpd = make_server('', 8000, application) print "Serving HTTP on port 8000..." # 开始监听HTTP请求: httpd.serve_forever()
运行python server.py启动服务;
然后在浏览器里面输入http://localhost:8000就能看到结果了。
在这里例子中,wsgiref实现了web服务器的功能,若用于生产,一般会使用apache或者nginx来做web服务器,然后让apache/nginx接收的web请求通过wsgi传送给web应用程序处理。
如上图所示,wsgiref、paste python库都实现了服务器与wsgi接口功能。django、flask等应用框架则实现了服务器、wsgi接口以及web应用的部分功能。