django源码笔记-【2】
上一期完理解了WSGI处理思路,现在看看django是如何实现这个接口的。
django.core.handlers
在此模块中着重看两个文件:base.py, wsgi.py
首先从宏观上看主要涉及到的类:
而当我们运行了manage.py runserver后,将会生成一个进程来运行WSGIHandler实例,来响应用户的请求,其实WSGIHandler就是一个上篇提到的app。
好了,现在关键就是WSGIHandler的__call__方法。
WSGIHandler.__call__
代码如下(可现暂时略过):
def __call__(self, environ, start_response):
from django.conf import settings
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._request_middleware is None:
self.initLock.acquire()
try:
try:
# Check that middleware is still uninitialised.
if self._request_middleware is None:
self.load_middleware()
except:
# Unload whatever middleware we got
self._request_middleware = None
raise
finally:
self.initLock.release()
set_script_prefix(base.get_script_name(environ))
signals.request_started.send(sender=self.__class__)
try:
try:
request = self.request_class(environ)
except UnicodeDecodeError:
logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
exc_info=sys.exc_info(),
extra={
'status_code': 400,
'request': request
}
)
response = http.HttpResponseBadRequest()
else:
response = self.get_response(request)
finally:
signals.request_finished.send(sender=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()]
for c in response.cookies.values():
response_headers.append(('Set-Cookie', str(c.output(header=''))))
start_response(status, response_headers)
return response
由代码我们知道
django把middleware分为了5类,分别是:
-
request_middleware
-
view_middleware
-
template_response_middleware
-
response_middleware
-
exception_middleware
django通过类中的对应的方法判断属于哪个类别
-
类别
方法
request_middleware
process_request
view_middleware
process_view
template_response_middleware
process_template_response
response_middleware
process_response
exception_middleware
process_exception
所以django的处理路径如下图所示:
Request_middle → View_middleware → View → Exception_middleware → template_response_middleware → Response_middleware
其实django就是使用一个handler作为一个wrapper将所有的app,middleware包裹在一起,并且按照上面的顺序进行处理,这样的好处是:
思路清晰,利于代码的维护,便于代码的扩展,并且将各个相对独立的步骤分割开来,互补影响。
o(∩∩)o...