def load_middleware(self):
"""
Populate middleware lists from settings.MIDDLEWARE.
Must be called after the environment is fixed (see __call__ in subclasses).
"""
self._view_middleware = []
self._template_response_middleware = []
self._exception_middleware = []
handler = convert_exception_to_response(self._get_response) handle1 #不同于其他handle,相当一个出口,在图二中相当于中心,执行view视图逻辑
for middleware_path in reversed(settings.MIDDLEWARE):
middleware = import_string(middleware_path)
try:
#初始化每个middleware并且,把handle传入
这个handler是上一个的middleware实体
mw_instance = middleware(handler)
#hander每次不一样
handler = convert_exception_to_response(mw_instance) handle[i]
... ...
self._middleware_chain = handler handle2 #相当于一个进口,进入中间件中
handler = convert_exception_to_response(self._get_response)
mw_instance = middleware(handler)。#实体
handler = convert_exception_to_response (mw_instance) #mw_instance(request) #调用实体的call方法
convert_exception_to_response是一个装饰器:
def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 500 responses.
This decorator is automatically applied to all middleware to ensure that
no middleware leaks an exception and that the next middleware in the stack
can rely on getting a response instead of an exception.
"""
@wraps(get_response)
def inner(request):
try:
response = get_response(request)
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
(1)、handler = convert_exception_to_response (mw_instance) = mw_instance = self.get_response
(2)、self._middleware_chain(request) = handle(request) = response = get_response(request)= mw_instance(request)=self.get_response(request)
class MiddlewareMixin:
def __init__(self, get_response=None):
self.get_response = get_response
super().__init__()
def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
response = response or self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response
1、最先进行流程处理的中间件,其process_request()(如果存在的话)最先被执行,但是其process_response()(如果存在的话)却最后得到处理,因为只有执行完后面的get_response()前面的才能接着执行。
2、最后进行流程处理的中间件,其process_request()(如果存在的话)最后被执行,但是其process_response()(如果存在的话)紧接着得到处理。
3、在中间件处理流程中,如果出现某个中间件的process_request()返回了response,这种情况通常是处理过程中出现了异常情况,该中间件后续的中间件不再参与处理,直接调用该中间件的process_response()(如果存在的话),或者直接返回。