在Python Web开发中,我们一般使用Flask
、Django
等web框架来开发应用程序,生产环境中将应用部署到Apache
、Nginx
等web服务器时,还需要uWSGI
或者Gunicorn
。一个完整的部署应该类似这样:
Web Server(Nginx、Apache) <-----> WSGI server(uWSGI、Gunicorn) <-----> App(Flask、Django)
要弄清这些概念之间的关系,就需要先理解WSGI
协议。
WSGI
的全称是Python Web Server Gateway Interface
,WSGI
不是web服务器,python模块,或者web框架以及其它任何软件,它只是一种规范,描述了web server
如何与web application
进行通信的规范。PEP-3333有关于WSGI
的具体定义。
我们使用web框架进行web应用程序开发时,只专注于业务的实现,HTTP协议层面相关的事情交于web服务器来处理,那么,Web服务器和应用程序之间就要知道如何进行交互。有很多不同的规范来定义这些交互,最早的一个是CGI,后来出现了改进CGI性能的FasgCGI。Java有专用的Servlet
规范,实现了Servlet API的Java web框架开发的应用可以在任何实现了Servlet API的web服务器上运行。WSGI
的实现受Servlet
的启发比较大。
在WSGI
中有两种角色:一方称之为server
或者gateway
, 另一方称之为application
或者framework
。application
可以提供一个可调用对象供server
调用。server
先收到用户的请求,然后调用application
提供的可调用对象,调用的结果会被封装成HTTP响应后发送给客户端。
WSGI
对application
的要求有3个:
- 实现一个可调用对象
- 可调用对象接收两个参数,
environ
(一个dict
,包含WSGI
的环境信息)与start_response
(一个响应请求的函数) - 返回一个
iterable
可迭代对象
可调用对象可以是一个函数、类或者实现了__call__
方法的类实例。
environ
和start_response
由server
方提供。
environ
是包含了环境信息的字典。
start_response
也是一个callable,接受两个必须的参数,status
(HTTP状态)和response_headers
(响应消息的头),可调用对象返回前调用start_response
。
下面是PEP-3333实现简单application
的代码:
HELLO_WORLD = b"Hello world!\n"
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [HELLO_WORLD]
class AppClass:
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def __iter__(self):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
self.start(status, response_headers)
yield HELLO_WORLD
代码分别用函数与类对application
的可调用对象进行了实现。类实现中定义了__iter__
方法,返回的类实例就变为了iterable可迭代对象。
我们也可以用定义了__call__方法的类实例做一下实现:
class AppClass:
def __call__(self, environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [HELLO_WORLD]
server
要做的是每次收到HTTP请求时,调用application
可调用对象,pep文档代码:
import os, sys
enc, esc = sys.getfilesystemencoding(), 'surrogateescape'
def unicode_to_wsgi(u):
# Convert an environment variable to a WSGI "bytes-as-unicode" string
return u.encode(enc, esc).decode('iso-8859-1')
def wsgi_to_bytes(s):
return s.encode('iso-8859-1')
def run_with_cgi(application):
environ = {k: unicode_to_wsgi(v) for k,v in os.environ.items()}
environ['wsgi.input'] = sys.stdin
environ['wsgi.errors'] = sys.stderr
environ['wsgi.version'] = (1, 0)
environ['wsgi.multithread'] = False
environ['wsgi.multiprocess'] = True
environ['wsgi.run_once'] = True
if environ.get('HTTPS', 'off') in ('on', '1'):
environ['wsgi.url_scheme'] = 'https'
else:
environ['wsgi.url_scheme'] = 'http'
headers_set = []
headers_sent = []
def write(data):
out = sys.stdout
if not headers_set:
raise AssertionError("write() before start_response()")
elif not headers_sent:
# Before the first output, send the stored headers
status, response_headers = headers_sent[:] = headers_set
out.write(wsgi_to_bytes('Status: %s\r\n' % status))
for header in response_headers:
out.write(wsgi_to_bytes('%s: %s\r\n' % header))
out.write(wsgi_to_bytes('\r\n'))
out.write(data)
out.flush()
def start_response(status, response_headers, exc_info=None):
if exc_info:
try:
if headers_sent:
# Re-raise original exception if headers sent
raise exc_info[1].with_traceback(exc_info[2])
finally:
exc_info = None # avoid dangling circular ref
elif headers_set:
raise AssertionError("Headers already set!")
headers_set[:] = [status, response_headers]
# Note: error checking on the headers should happen here,
# *after* the headers are set. That way, if an error
# occurs, start_response can only be re-called with
# exc_info set.
return write
result = application(environ, start_response)
try:
for data in result:
if data: # don't send headers until body appears
write(data)
if not headers_sent:
write('') # send headers now if body was empty
finally:
if hasattr(result, 'close'):
result.close()
代码中server
组装了environ
,定义了start_response
函数,将两个参数提供给application
并且调用,最后输出HTTP响应的status
、header
和body
:
if __name__ == '__main__':
run_with_cgi(simple_app)
输出:
Status: 200 OK
Content-type: text/plain
Hello world!
environ
字典包含了一些CGI
规范要求的数据,以及WSGI
规范新增的数据,还可能包含一些操作系统的环境变量以及Web服务器相关的环境变量,具体见environ。
首先是CGI规范中要求的变量:
- REQUEST_METHOD: HTTP请求方法,
GET
,POST
等,不能为空 - SCRIPT_NAME: HTTP请求path中的初始部分,用来确定对应哪一个
application
,当application
对应于服务器的根,可以为空 - PATH_INFO: path中剩余的部分,
application
要处理的部分,可以为空 - QUERY_STRING: HTTP请求中的查询字符串,URL中?后面的内容
- CONTENT_TYPE: HTTP headers中的
Content-Type
内容 - CONTENT_LENGTH: HTTP headers中的
Content-Length
内容 - SERVER_NAME和SERVER_PORT: 服务器域名和端口,这两个值和前面的
SCRIPT_NAME
,PATH_INFO
拼起来可以得到完整的URL路径 - SERVER_PROTOCOL: HTTP协议版本,
HTTP/1.0
或HTTP/1.1
- HTTP_Variables: 和HTTP请求中的headers对应,比如
User-Agent
写成HTTP_USER_AGENT
的格式
WSGI规范中还要求environ包含下列成员:
- wsgi.version:一个元组(1, 0),表示
WSGI
版本1.0 - wsgi.url_scheme:
http
或者https
- wsgi.input:一个类文件的输入流,
application
可以通过这个获取HTTP请求的body - wsgi.errors:一个输出流,当应用程序出错时,可以将错误信息写入这里
- wsgi.multithread:当
application
对象可能被多个线程同时调用时,这个值需要为True - wsgi.multiprocess:当
application
对象可能被多个进程同时调用时,这个值需要为True - wsgi.run_once:当
server
期望application
对象在进程的生命周期内只被调用一次时,该值为True
我们可以使用python官方库wsgiref
实现的server
看一下environ
的具体内容:
def demo_app(environ, start_response):
from StringIO import StringIO
stdout = StringIO()
print >>stdout, "Hello world!"
print >>stdout
h = environ.items()
h.sort()
for k,v in h:
print >>stdout, k,'=', repr(v)
start_response("200 OK", [('Content-Type','text/plain')])
return [stdout.getvalue()]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('', 8000, demo_app)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
import webbrowser
webbrowser.open('http://localhost:8000/xyz?abc')
httpd.handle_request() # serve one request, then exit
httpd.server_close()
打开的网页会输出environ
的具体内容。
使用environ
组装请求URL地址:
from urllib.parse import quote
url = environ['wsgi.url_scheme']+'://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
if environ['wsgi.url_scheme'] == 'https':
if environ['SERVER_PORT'] != '443':
url += ':' + environ['SERVER_PORT']
else:
if environ['SERVER_PORT'] != '80':
url += ':' + environ['SERVER_PORT']
url += quote(environ.get('SCRIPT_NAME', ''))
url += quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
start_response
是一个可调用对象,接收两个必选参数和一个可选参数:
status
: 一个字符串,表示HTTP响应状态字符串,比如200 OK
、404 Not Found
headers
: 一个列表,包含有如下形式的元组:(header_name, header_value)
,用来表示HTTP响应的headers
exc_info
(可选): 用于出错时,server
需要返回给浏览器的信息
start_response
必须返回一个write(body_data)
可调用对象。
我们知道HTTP的响应需要包含status
,headers
和body
,所以在application
对象将body
作为返回值return之前,需要先调用start_response
,将status
和headers
的内容返回给server
,这同时也是告诉server
,application
对象要开始返回body了。
由此可见,server
负责接收HTTP请求,根据请求数据组装environ
,定义start_response
函数,将这两个参数提供给application
。application
根据environ
信息执行业务逻辑,将结果返回给server
。响应中的status
、headers
由start_response
函数返回给server
,响应的body
部分被包装成iterable
作为application
的返回值,server
将这些信息组装为HTTP响应返回给请求方。
在一个完整的部署中,uWSGI
和Gunicorn
是实现了WSGI
的server
,Django
、Flask
是实现了WSGI
的application
。两者结合起来其实就能实现访问功能。实际部署中还需要Nginx
、Apache
的原因是它有很多uWSGI
没有支持的更好功能,比如处理静态资源,负载均衡等。Nginx
、Apache
一般都不会内置WSGI
的支持,而是通过扩展来完成。比如Apache
服务器,会通过扩展模块mod_wsgi
来支持WSGI
。Apache
和mod_wsgi
之间通过程序内部接口传递信息,mod_wsgi
会实现WSGI
的server
端、进程管理以及对application
的调用。Nginx
上一般是用proxy的方式,用Nginx
的协议将请求封装好,发送给应用服务器,比如uWSGI
,uWSGI
会实现WSGI
的服务端、进程管理以及对application
的调用。
uWSGI
与Gunicorn
的比较,由链接可知:
在响应时间较短的应用中,uWSGI+django是个不错的组合(测试的结果来看有稍微那么一点优势),但是如果有部分阻塞请求 Gunicorn+gevent+django有非常好的效率, 如果阻塞请求比较多的话,还是用tornado重写吧。
WSGI
除了server
和application
两个角色外,还有middleware
中间件,middleware
运行在server
和application
中间,同时具备server
和application
的角色,对于server
来说,它是一个application
,对于application
来说,它是一个server
:
from piglatin import piglatin
class LatinIter:
def __init__(self, result, transform_ok):
if hasattr(result, 'close'):
self.close = result.close
self._next = iter(result).__next__
self.transform_ok = transform_ok
def __iter__(self):
return self
def __next__(self):
if self.transform_ok:
return piglatin(self._next()) # call must be byte-safe on Py3
else:
return self._next()
class Latinator:
# by default, don't transform output
transform = False
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
transform_ok = []
def start_latin(status, response_headers, exc_info=None):
# Reset ok flag, in case this is a repeat call
del transform_ok[:]
for name, value in response_headers:
if name.lower() == 'content-type' and value == 'text/plain':
transform_ok.append(True)
# Strip content-length if present, else it'll be wrong
response_headers = [(name, value)
for name, value in response_headers
if name.lower() != 'content-length'
]
break
write = start_response(status, response_headers, exc_info)
if transform_ok:
def write_latin(data):
write(piglatin(data)) # call must be byte-safe on Py3
return write_latin
else:
return write
return LatinIter(self.application(environ, start_latin), transform_ok)
from foo_app import foo_app
run_with_cgi(Latinator(foo_app))
可以看出,Latinator
调用foo_app
充当server
角色,然后实例被run_with_cgi
调用充当application
角色。
- uwsgi:与
WSGI
一样是一种通信协议,是uWSGI
服务器的独占协议,据说该协议是fastcgi
协议的10倍快。 - uWSGI:是一个
web server
,实现了WSGI
协议、uwsgi
协议、http
协议等。
每个Django项目中都有个wsgi.py文件,作为application
是这样实现的:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
源码:
from django.core.handlers.wsgi import WSGIHandler
def get_wsgi_application():
django.setup(set_prefix=False)
return WSGIHandler()
WSGIHandler
:
class WSGIHandler(base.BaseHandler):
request_class = WSGIRequest
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load_middleware()
def __call__(self, environ, start_response):
set_script_prefix(get_script_name(environ))
signals.request_started.send(sender=self.__class__, environ=environ)
request = self.request_class(environ)
response = self.get_response(request)
response._handler_class = self.__class__
status = '%d %s' % (response.status_code, response.reason_phrase)
response_headers = [
*response.items(),
*(('Set-Cookie', c.output(header='')) for c in response.cookies.values()),
]
start_response(status, response_headers)
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
response = environ['wsgi.file_wrapper'](response.file_to_stream)
return response
application
是一个定义了__call__方法的WSGIHandler
类实例,首先加载中间件,然后根据environ
生成请求request
,根据请求生成响应response
,status
和response_headers
由start_response
处理,然后返回响应body。
Django
也自带了WSGI server
,当然性能不够好,一般用于测试用途,运行runserver
命令时,Django
可以起一个本地WSGI server
,django/core/servers/basehttp.py
文件:
def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer):
server_address = (addr, port)
if threading:
httpd_cls = type('WSGIServer', (socketserver.ThreadingMixIn, server_cls), {})
else:
httpd_cls = server_cls
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
if threading:
httpd.daemon_threads = True
httpd.set_app(wsgi_handler)
httpd.serve_forever()
实现的WSGIServer
,继承自wsgiref
:
class WSGIServer(simple_server.WSGIServer):
"""BaseHTTPServer that implements the Python WSGI protocol"""
request_queue_size = 10
def __init__(self, *args, ipv6=False, allow_reuse_address=True, **kwargs):
if ipv6:
self.address_family = socket.AF_INET6
self.allow_reuse_address = allow_reuse_address
super().__init__(*args, **kwargs)
def handle_error(self, request, client_address):
if is_broken_pipe_error():
logger.info("- Broken pipe from %s\n", client_address)
else:
super().handle_error(request, client_address)