在Python Web開發中,我們一般使用Flask、Django等web框架來開發應用程序,生產環境中將應用部署到Apache、Nginx等web服務器時,還需要uWSGI或者Gunicorn。一個完整的部署應該類似這樣:
Web Server(Nginx、Apache) <-----> WSGI server(uWSGI、Gunicorn) <-----> App(Flask、Django)
要弄清這些概念之間的關系,就需要先理解WSGI協議。
WSGI是什么
WSGI的全稱是Python Web Server Gateway Interface,WSGI不是web服務器,python模塊,或者web框架以及其它任何軟件,它只是一種規范,描述了web server如何與web application進行通信的規范。PEP-3333有關於WSGI的具體定義。
為什么需要WSGI
我們使用web框架進行web應用程序開發時,只專注於業務的實現,HTTP協議層面相關的事情交於web服務器來處理,那么,Web服務器和應用程序之間就要知道如何進行交互。有很多不同的規范來定義這些交互,最早的一個是CGI,后來出現了改進CGI性能的FasgCGI。Java有專用的Servlet規范,實現了Servlet API的Java web框架開發的應用可以在任何實現了Servlet API的web服務器上運行。WSGI的實現受Servlet的啟發比較大。
WSGI的實現
在WSGI中有兩種角色:一方稱之為server或者gateway, 另一方稱之為application或者framework。application可以提供一個可調用對象供server調用。server先收到用戶的請求,然后調用application提供的可調用對象,調用的結果會被封裝成HTTP響應后發送給客戶端。
The Application/Framework Side
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]
The Server/Gateway Side
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
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_resposne
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重寫吧。
Middleware
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、uwsgi與WSGI的區別
- uwsgi:與WSGI一樣是一種通信協議,是uWSGI服務器的獨占協議,據說該協議是fastcgi協議的10倍快。
- uWSGI:是一個web server,實現了WSGI協議、uwsgi協議、http協議等。
Django中WSGI的實現
每個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)
參考鏈接
- pep-3333
- WSGI簡介
