WSGI

2018-02-09  本文已影响0人  Alex_Dj

简介

Web服务器网关接口(WSGI)是用于Python编程语言的Web服务器(Web Server)Web应用程序或框架(Web application or frameworks)之间的简单通用接口的规范。

WSGI有两端:一端是“服务器(server)”或“网关(gateway)”(通常是诸如Apache或Nginx的Web服务器);另一端是“应用程序”或“框架”。为了处理WSGI请求,服务器端执行应用程序,并向应用程序端提供环境信息和回调函数。应用程序处理请求,并使用它提供的回调函数将响应返回给服务器端。

在服务器和应用程序之间可能会有一个WSGI中间件,它实现了两端的API。服务器收到来自客户端的请求,并将其转发给中间件。处理完成后,它向应用程序发送一个请求。应用程序的响应由中间件转发到服务器,最终转发给客户端。可能有多个中间件形成一个WSGI兼容应用程序的堆栈。

“中间件”组件可以实现如下功能:

Python WSGI接口

我们来看下整体的结构图:


WSGI结构图
应用端接口

再Python 3.5中,应用程序端的接口如下所示:

def application(environ, start_response):
    body = b'Hello world!\n'
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return [body]

这里的应用程序对象的规范是:

服务器端接口

WSGI服务器与这个应用程序的接口如下:

def write(chunk):
    '''Write data back to client'''
    ...

def send_status(status):
   '''Send HTTP status code'''
   ...

def send_headers(headers):
    '''Send HTTP headers'''
    ...

def start_response(status, headers):
    '''WSGI start_response callable'''
    send_status(status)
    send_headers(headers)
    return write

# Make request to application
response = application(environ, start_response)
try:
    for chunk in response:
        write(chunk)
finally:
    if hasattr(response, 'close'):
        response.close()
参考
  1. Web Server Gateway Interface
  2. WSGI: The Server-Application Interface for Python
  3. flask 源码解析:应用启动流程
上一篇 下一篇

猜你喜欢

热点阅读