sequenceDiagram
Browser->>Web Server: Http Request
Web Server->>Web Server: Generate a HTML page
Web Server->>Browser: Http Response with HTML page as body
Browser->>Browser: Get the HTML page and display
从代码中可以发现,接收 http request,生成 http response 是个苦力活,而生成 html 页面更加容易,因此就把这些底层内容教给服务器程序去干,并通过 WSGI 协议向我们提供服务。
WSGI 就是 Python 定义的一个协议,只要我们按照这个协议编写 Web App,就能通过 WSGI 处理 HTTP 请求和响应。
WSGI 协议包括两部分:Web Application 和 Gateway。Gateway (Web Server) 接收请求后,将数据以规定格式传递给 Web Application,Web Application 处理完后,设置对应的 Status 和 Header,并将数据返回给 Gateway,而 Gateway 将返回的数据进行封装,最终返回一个完整的 Http Response。
result = application(environ, start_response) try: for data in result: # 如果没有 body 数据,则不发送响应头 if data: write(data) # 若 body 为空,则发送响应头 ifnot headers_sent: write('') finally: if hasattr(result, "close"): result.close()
if __name__ == "__main__": run_with_cgi(simple_app)
classBaseHandler: """Manage the invocation of a WSGI application"""
...
defrun(self, application): """Invoke the application""" # Note to self: don't move the close()! Asynchronous servers shouldn't # call close() from finish_response(), so if you close() anywhere but # the double-error branch here, you'll break asynchronous servers by # prematurely closing. Async servers must return from 'run()' without # closing if there might still be output to iterate over. try: self.setup_environ() self.result = application(self.environ, self.start_response) self.finish_response() except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError): ... ...