This article is the second in a series of articles on building a Web site in Python. Following the above, it mainly tells you the relevant information about the Web server gateway interface WSGI. It is very detailed. Friends who need it can refer to it
In the Web server and Web framework for building a Web site in Python, we have clarified the concepts of Web server, Web application, and Web framework. For Python, more and more web frameworks are coming out, which not only gives us more choices, but also limits our choices for web servers. There are also many Web frameworks in Java. Because of the servlet API, any application written by the Java Web framework can run on any Web Server.
Of course the Python community also needs such a set of APIs to adapt to web servers and applications. This set of APIs is WSGI (Python Web Server Gateway Interface), which is described in detail in PEP 3333. Simply put, WSGI is a bridge connecting web servers and web applications. On the one hand, it gets the original HTTP data from the web server, processes it into a unified format and then hands it to the web application. On the other hand, it conducts business from the application/framework side. Logical processing, generates response content and hands it to the server.
The detailed process of coupling the Web server and the framework through WSGI is shown in the figure below:
WSGI Server Adaptation
Detailed explanation As follows:
The application (network framework) provides a callable object named application (the WSGI protocol does not specify how to implement this object). Each time the server receives a request from an HTTP client, it calls the callable object application, passing a dictionary named environ as a parameter and a callable object named start_response. The framework/application generates the HTTP status code and HTTP response headers, then passes both to start_response and waits for the server to save them. Additionally, the framework/app will return the body of the response. The server combines the status code, response header and response body into an HTTP response and returns it to the client (this step does not belong to the WSGI protocol).
Let’s take a look at how WSGI adapts from the server side and the application side respectively.
Server side
We know that each HTTP request issued by the client (usually a browser) consists of three parts: the request line, the message header, and the request body. Contains relevant details of this request. For example:
Method: Indicates the method executed on the resource identified by Request-URI, including GET, POST, etc. User-Agent: allows the client to use its operating system, browser and other The attribute tells the server;
After the server receives the HTTP request from the client, the WSGI interface must unify these request fields so that they can be passed to the application server interface (actually to the framework). The specific data that the web server passes to the application has been specified in detail as early as CGI (Common Gateway Interface, Common Gateway Interface). These data are called CGI environment variables. WSGI inherits the contents of CGI environment variables and requires the Web server to create a dictionary to save these environment variables (usually named environ). In addition to variables defined by CGI, environ must also save some variables defined by WSGI. In addition, it can also save some environment variables of the client system. You can refer to environ Variables to see what specific variables there are.
Then the WSGI interface must hand environ to the application for processing. Here WSGI stipulates that the application provides a callable object application, and then the server calls application and obtains the return value as the HTTP response body. When the server calls application, it needs to provide two variables, one is the variable dictionary environ mentioned earlier, and the other is the callable object start_response, which generates status codes and response headers, so that we get a complete HTTP response. The web server returns the response to the client, and a complete HTTP request-response process is completed.
wsgiref Analysis
Python has a built-in web server that implements the WSGI interface. In the module wsgiref, it is a reference implementation of the WSGI server written in pure Python. , let’s briefly analyze its implementation. First, assume that we start a Web server with the following code:
# Instantiate the server httpd = make_server( 'localhost', # The host name 8051, # A port number where to wait for the request application # The application object name, in this case a function ) # Wait for a single request, serve it and quit httpd.handle_request()
Then we use the Web server to receive a request, generate environ, and then call application to process the request. The main line is used to analyze the calling process of the source code, which is simplified as shown in the following figure:
WSGI Server calling process
这里主要有三个类,WSGIServer,WSGIRequestHandler,ServerHandle。WSGIServer 是Web服务器类,可以提供server_address(IP:Port)和 WSGIRequestHandler 类来进行初始化获得一个server对象。该对象监听响应的端口,收到HTTP请求后通过 finish_request 创建一个RequestHandler 类的实例,在该实例的初始化过程中会生成一个 Handle 类实例,然后调用其 run(application) 函数,在该函数里面再调用应用程序提供的 application对象来生成响应。
这三个类的继承关系如下图所示:
WSGI 类继承关系图
其中 TCPServer 使用 socket 来完成 TCP 通信,HTTPServer 则是用来做 HTTP 层面的处理。同样的,StreamRequestHandler 来处理 stream socket,BaseHTTPRequestHandler 则是用来处理 HTTP 层面的内容,这部分和 WSGI 接口关系不大,更多的是 Web 服务器的具体实现,可以忽略。
微服务器实例
如果上面的 wsgiref 过于复杂的话,下面一起来实现一个微小的 Web 服务器,便于我们理解 Web 服务器端 WSGI 接口的实现。代码摘自 自己动手开发网络服务器(二),放在 gist 上,主要结构如下:
class WSGIServer(object): # 套接字参数 address_family, socket_type = socket.AF_INET, socket.SOCK_STREAM request_queue_size = 1 def __init__(self, server_address): # TCP 服务端初始化:创建套接字,绑定地址,监听端口 # 获取服务器地址,端口 def set_app(self, application): # 获取框架提供的 application self.application = application def serve_forever(self): # 处理 TCP 连接:获取请求内容,调用处理函数 def handle_request(self): # 解析 HTTP 请求,获取 environ,处理请求内容,返回HTTP响应结果 env = self.get_environ() result = self.application(env, self.start_response) self.finish_response(result) def parse_request(self, text): # 解析 HTTP 请求 def get_environ(self): # 分析 environ 参数,这里只是示例,实际情况有很多参数。 env['wsgi.url_scheme'] = 'http' ... env['REQUEST_METHOD'] = self.request_method # GET ... return env def start_response(self, status, response_headers, exc_info=None): # 添加响应头,状态码 self.headers_set = [status, response_headers + server_headers] def finish_response(self, result): # 返回 HTTP 响应信息 SERVER_ADDRESS = (HOST, PORT) = '', 8888 # 创建一个服务器实例 def make_server(server_address, application): server = WSGIServer(server_address) server.set_app(application) return server
目前支持 WSGI 的成熟Web服务器有很多,Gunicorn是相当不错的一个。它脱胎于ruby社区的Unicorn,成功移植到python上,成为一个WSGI HTTP Server。有以下优点:
容易配置 可以自动管理多个worker进程 选择不同的后台扩展接口(sync, gevent, tornado等) 应用程序端(框架)
和服务器端相比,应用程序端(也可以认为框架)要做的事情就简单很多,它只需要提供一个可调用对象(一般习惯将其命名为application),这个对象接收服务器端传递的两个参数 environ 和 start_response。这里的可调用对象不仅可以是函数,还可以是类(下面第二个示例)或者拥有 __call__ 方法的实例,总之只要可以接受前面说的两个参数,并且返回值可以被服务器进行迭代即可。
Application 具体要做的就是根据 environ 里面提供的关于 HTTP 请求的信息,进行一定的业务处理,返回一个可迭代对象,服务器端通过迭代这个对象,来获得 HTTP 响应的正文。如果没有响应正文,那么可以返回None。
同时,application 还会调用服务器提供的 start_response,产生HTTP响应的状态码和响应头,原型如下:
def start_response(self, status, headers,exc_info=None):
Application 需要提供 status:一个字符串,表示HTTP响应状态字符串,还有 response_headers: 一个列表,包含有如下形式的元组:(header_name, header_value),用来表示HTTP响应的headers。同时 exc_info 是可选的,用于出错时,server需要返回给浏览器的信息。
到这里为止,我们就可以实现一个简单的 application 了,如下所示:
def simple_app(environ, start_response): """Simplest possible application function""" HELLO_WORLD = "Hello world!\n" status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return [HELLO_WORLD]
或者用类实现如下。
class AppClass: """Produce the same output, but using a class""" def __init__(self, environ, start_response): self.environ = environ self.start = start_response def __iter__(self): ... HELLO_WORLD = "Hello world!\n" yield HELLO_WORLD
注意这里 AppClass 类本身就是 application,用 environ 和 start_response 调用(实例化)它返回一个实例对象,这个实例对象本身是可迭代的,符合 WSGI 对 application 的要求。
如果想使用 AppClass 类的对象作为 application,那么必须给类添加一个 __call__ 方法,接受 environ 和 start_response 为参数,返回可迭代对象,如下所示:
class AppClass: """Produce the same output, but using an object""" def __call__(self, environ, start_response):
这部分涉及到python的一些高级特性,比如 yield 和 magic method,可以参考我总结的python语言要点来理解。
Flask 中的 WSGI
flask 是一个轻量级的Python Web框架,符合 WSGI 的规范要求。它的最初版本只有 600 多行,相对便于理解。下面我们来看下它最初版本中关于 WSGI 接口的部分。
def wsgi_app(self, environ, start_response): """The actual WSGI application. This is not implemented in `__call__` so that middlewares can be applied: app.wsgi_app = MyMiddleware(app.wsgi_app) """ with self.request_context(environ): rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() response = self.make_response(rv) response = self.process_response(response) return response(environ, start_response) def __call__(self, environ, start_response): """Shortcut for :attr:`wsgi_app`""" return self.wsgi_app(environ, start_response)
这里的 wsgi_app 实现了我们说的 application 功能,rv 是 对请求的封装,response 是框架用来处理业务逻辑的具体函数。这里对 flask 源码不做过多解释,感兴趣的可以去github下载,然后check 到最初版本去查看。
中间件
前面 flask 代码 wsgi_app 函数的注释中提到不直接在 __call__ 中实现 application 部分,是为了可以使用中间件。 那么为什么要使用中间件,中间件又是什么呢?
回顾前面的 application/server 端接口,对于一个 HTTP 请求,server 端总是会调用一个 application 来进行处理,并返回 application 处理后的结果。这足够应付一般的场景了,不过并不完善,考虑下面的几种应用场景:
对于不同的请求(比如不同的 URL),server 需要调用不同的 application,那么如何选择调用哪个呢; 为了做负载均衡或者是远程处理,需要使用网络上其他主机上运行的 application 来做处理; 需要对 application 返回的内容做一定处理后才能作为 HTTP 响应;
上面这些场景有一个共同点就是,有一些必需的操作不管放在服务端还是应用(框架)端都不合适。对应用端来说,这些操作应该由服务器端来做,对服务器端来说,这些操作应该由应用端来做。为了处理这种情况,引入了中间件。
中间件就像是应用端和服务端的桥梁,来沟通两边。对服务器端来说,中间件表现的像是应用端,对应用端来说,它表现的像是服务器端。如下图所示:
中间件
中间件的实现
flask 框架在 Flask 类的初始化代码中就使用了中间件:
self.wsgi_app = SharedDataMiddleware(self.wsgi_app, { self.static_path: target })
这里的作用和 python 中的装饰器一样,就是在执行 self.wsgi_app 前后执行 SharedDataMiddleware 中的一些内容。中间件做的事,很类似python中装饰器做的事情。SharedDataMiddleware 中间件是 werkzeug 库提供的,用来支持站点托管静态内容。此外,还有DispatcherMiddleware 中间件,用来支持根据不同的请求,调用不同的 application,这样就可以解决前面场景 1, 2 中的问题了。
下面来看看 DispatcherMiddleware 的实现:
class DispatcherMiddleware(object): """Allows one to mount middlewares or applications in a WSGI application. This is useful if you want to combine multiple WSGI applications:: app = DispatcherMiddleware(app, { '/app2': app2, '/app3': app3 }) """ def __init__(self, app, mounts=None): self.app = app self.mounts = mounts or {} def __call__(self, environ, start_response): script = environ.get('PATH_INFO', '') path_info = '' while '/' in script: if script in self.mounts: app = self.mounts[script] break script, last_item = script.rsplit('/', 1) path_info = '/%s%s' % (last_item, path_info) else: app = self.mounts.get(script, self.app) original_script_name = environ.get('SCRIPT_NAME', '') environ['SCRIPT_NAME'] = original_script_name + script environ['PATH_INFO'] = path_info return app(environ, start_response)
初始化中间件时需要提供一个 mounts 字典,用来指定不同 URL 路径到 application 的映射关系。这样对于一个请求,中间件检查其路径,然后选择合适的 application 进行处理。
关于 WSGI 的原理部分基本结束,下一篇我会介绍下对 flask 框架的理解。
更多Python 搭建Web站点之Web服务器网关接口相关文章请关注PHP中文网!