WSGI 有三個部分, 分別為服務器(server), 應用程序(application) 和中間件(middleware). 已經知道, 服務器方面會調用應用程序來處理請求, 在應用程序中有真正的處理邏輯, 在這里面幾乎可以做任何事情, 其中的中間件就會在里面展開.
Django 中的應用程序
任何的 WSGI 應用程序, 都必須是一個 start_response(status, response_headers, exc_info=None) 形式的函數或者定義了 __call__ 的類. 而 django.core.handlers 就用后一種方式實現了應用程序: WSGIHandler. 在這之前, Django 是如何指定自己的 application 的, 在一個具體的 Django 項目中, 它的方式如下:
在 mysite.settings.py 中能找到如下設置:
# Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'tomato.wsgi.application'
如你所見, WSGI_APPLICATION 就指定了應用程序. 而按圖索驥下去, 找到項目中的 wsgi.py, 已經除去了所有的注釋:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomato.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
因此, WSGI_APPLICATION 所指定的即為 wsgi.py 中的全局變量 application. 故伎重演, 繼續找下去. 在 django.core 模塊中的 wsgi.py 中找到 get_wsgi_application() 函數的實現:
from django.core.handlers.wsgi import WSGIHandler
def get_wsgi_application():
"""
The public interface to Django's WSGI support. Should return a WSGI
callable.
Allows us to avoid making django.core.handlers.WSGIHandler public API, in
case the internal WSGI implementation changes or moves in the future.
"""
"""
# 繼承, 但只實現了 __call__ 方法, 方便使用
class WSGIHandler(base.BaseHandler):
"""
return WSGIHandler()
在 get_wsgi_application() 中實例化了 WSGIHandler, 並無其他操作.
WSGIHandler
緊接着在 django.core.handler 的 base.py 中找到 WSGIHandler 的實現.
# 繼承, 但只實現了 __call__ 方法, 方便使用
class WSGIHandler(base.BaseHandler):
initLock = Lock()
# 關於此, 日后展開, 可以將其視為一個代表 http 請求的類
request_class = WSGIRequest
# WSGIHandler 也可以作為函數來調用
def __call__(self, environ, start_response):
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
# 這里的檢測: 因為 self._request_middleware 是最后才設定的, 所以如果為空,
# 很可能是因為 self.load_middleware() 沒有調用成功.
if self._request_middleware is None:
with self.initLock:
try:
# Check that middleware is still uninitialised.
if self._request_middleware is None:
因為 load_middleware() 可能沒有調用, 調用一次.
self.load_middleware()
except:
# Unload whatever middleware we got
self._request_middleware = None
raise
set_script_prefix(base.get_script_name(environ))
signls.request_started.send(sender=self.__class__) # __class__ 代表自己的類
try:
# 實例化 request_class = WSGIRequest, 將在日后文章中展開, 可以將其視為一個代表 http 請求的類
request = self.request_class(environ)
except UnicodeDecodeError:
logger.warning('Bad Request (UnicodeDecodeError)',
exc_info=sys.exc_info(),
extra={
'status_code': 400,
}
)
response = http.HttpResponseBadRequest()
else:
# 調用 self.get_response(), 將會返回一個相應對象 response
############# 關鍵的操作, self.response() 可以獲取響應數據.
response = self.get_response(request)
# 將 self 掛鈎到 response 對象
response._handler_class = self.__class__
try:
status_text = STATUS_CODE_TEXT[response.status_code]
except KeyError:
status_text = 'UNKNOWN STATUS CODE'
# 狀態碼
status = '%s %s' % (response.status_code, status_text)
response_headers = [(str(k), str(v)) for k, v in response.items()]
# 對於每個一個 cookie, 都在 header 中設置: Set-cookie xxx=yyy
for c in response.cookies.values():
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
# start_response() 操作已經在上節中介紹了
start_response(force_str(status), response_headers)
# 成功返回相應對象
return response
WSGIHandler 類只實現了 def __call__(self, environ, start_response), 使它本身能夠成為 WSGI 中的應用程序, 並且實現 __call__ 能讓類的行為跟函數一樣, 詳見 python __call__ 方法.
def __call__(self, environ, start_response) 方法中調用了 WSGIHandler.get_response() 方法以獲取響應數據對象 response. 從 WSGIHandler 的實現來看, 它並不是最為底層的: WSGIHandler 繼承自 base.BaseHandler, 在 django.core.handler 的 base.py 中可以找到: class BaseHandler(object):...
這一節服務器部分已經結束, 接下來的便是中間件和應用程序了, 相關內容會在下節的 BaseHandler 中展開. 我已經在 github 備份了 Django 源碼的注釋: Decode-Django, 有興趣的童鞋 fork 吧.
近來准備校園招聘, 生產效率較低, 九月份的空氣注定不安分 ;)
搗亂 2013-9-11
