一、中间件运作流程
1、自己的理解
2、参考的图
二、流程试例
process_request(self, request) process_view(self,request, callback,
call_args, call_kwargs) process_template_response(self, request,
response) process_exception(self, request, exception)
process_response(self, request, response)
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class MMM(object):
def __init__(self, get_response=None):
self.get_response = get_response
super(MMM, self).__init__()
def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
# 执行下一个__call__
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response
class MDW1(MMM):
def process_request(self, request):
print('mdw1-->process_request')
def process_view(self, request, view_func, view_args, view_kwargs):
print('mdw1-->process_view')
def process_response(self, request, response):
print('mdw1-->process_response')
return response
def process_exception(self, request, exception):
print('mdw1-->process_exception')
def process_template_response(self,request,response):
print('mdw1--> process_template_response')
return response
class MDW2(MMM):
def process_request(self, request):
print('mdw2-->process_request')
def process_view(self, request, view_func, view_args, view_kwargs):
print('mdw2-->process_view')
def process_response(self, request, response):
print('mdw2-->process_response')
return response
def process_exception(self, request, exception):
print('mdw2-->process_exception')
return HttpResponse('OK')
def process_template_response(self,request,response):
print('mdw2--> process_template_response')
return response
class MDW3(MMM):
def process_request(self, request):
print('mdw3-->process_request')
def process_view(self, request, view_func, view_args, view_kwargs):
print('mdw3-->process_view')
def process_response(self, request, response):
print('mdw3-->process_response')
return response
def process_exception(self, request, exception):
print('mdw3-->process_exception')
# return HttpResponse('OK')
# print('mdw3-->process_exception')
def process_template_response(self,request,response):
# print(request,type(request))
# print(response,type(response))
print('mdw3--> process_template_response')
return response