web server gateway interface:将http请求,响应格式封装起来,让我们可以专心的用python编写web业务。
WSGI接口定义的非常简单,它只要求开发者实现一个函数,就可以响应HTTP请求。
我们来看一个最简单的例子:
def application(environ,start_response): start_response('200 OK',[('content-type', 'text/html')]) return [b'<h1>Hello,Web</h1>']
上述application()函数就是符合WSGI标准的一个HTTP处理函数,它接收两个参数:
- environ:一个包含所有HTTP请求信息的dict对象。
- start_response:一个发送HTTP响应的函数。
有了WSGI,我们就可以从environ这个dict对象中拿到HTTP请求信息,然后构造HTML,通过start_response()发送Header,最后返回Body。
不过,这个application函数由谁调用呢?它必须由WSGI服务器来调用。有很多符合WSGI规范的服务器,我们可以找一个来用。
python中内置了一个WSGI服务器,这个模块叫做wsgiref,它是用纯python编写的WSGI服务器的参考实现。
总结:
无论多么复杂的Web应用程序,入口都是一个WSGI处理函数。HTTP请求的所有输入信息都可以通过environ
获得,HTTP响应的输出都可以通过start_response()
加上函数返回值作为Body。
复杂的Web应用程序,光靠一个WSGI函数来处理还是太底层了,我们需要在WSGI之上再抽象出Web框架,进一步简化Web开发。