5

Python WSGI规范

 2 years ago
source link: https://allenwind.github.io/blog/2065/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Mr.Feng Blog

NLP、深度学习、机器学习、Python、Go

Python WSGI规范

简单谈谈Python WSGI规范

WSGI规范

WSGI规范是Python Web开发中的底层基础。相对于http.server,现在的HTTP开始已经使用更通用的WSGI协议了。但WSGI不支持异步web服务器。

WSGI规范规定每个Application必须是一个可调用对象,这个可调用对象可以是类也可以是函数,实现了call方法,接受两个参数,environ和start_response函数,负责响应请求的函数,并返回一个可迭代对象。

其中,environ、start_response是HTTP服务器实现的。environ变量是包含环境信息的字典,每个application对象在返回前调用start_response。start_response也是可调用对象,可以传入两个参数:status、response_headers。

# 写入请求相关的信息写入environ变量,方便程序访问

def application(environ, start_response):
html_body = "WSGI Application\r\n"
status = "200 OK"

response_headers = [('Content-Type', 'text/plain'),('Content-Length', str(len(html_body)))]

start_response(status, response_headers)

// yield 可以使用yield返回信息

return [html_body]

那么,HTTP服务器上又如何处理envir和start_response呢?

import os
import sys

def run_wsgi(application):
environ = dict(os.environ.items())
environ['wsgi.input'] = sys.stdin
# else environ

headers_set = []
headers_sent = []

def write(data):
sys.stdout.write(data)
sys.stdout.flush()

def start_response(status, response_headers):
headers_set[:] = [status, response_headers]
return write

result = application(environ, start_response)

try:
for data in result:
if data:
write(data)
finally:
if hasattr(result, 'close'):
result.close()

Middleware

middleware位于服务器和应用程序之间,像管道一样在在两端传递请求相关的数据。具体操作如下:

  1. 被服务器调用,返回结果
  2. 调用应用程序,把参数传递过去

[1] PEP333

转载请包括本文地址:https://allenwind.github.io/blog/2065
更多文章请参考:https://allenwind.github.io/blog/archives/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK