1. What is the middleware (Django)?
For Django, the middleware is inherited from MiddlewareMixin (located in the module django.utils.deprecation) class, which processes the request (request) and the response (response) corresponding to a control method performed according to the rules, to the access control, rights management, request authentication, data cache, etc. effect.
In django2.x, the project will open the following default middleware, the middleware can be learned by looking at the source code,
These built middleware substantially rewriting the base class process_request (request, * args, ** kwargs) and process_response (request, response * args, ** kwargs) method,
Middleware (CsrfViewMiddleware, etc.) to rewrite the process_view (Self, Request, callback, callback_args, callback_kwargs)
Process views (views) performs an error handling is through process_exception (self, request, exception) controlled.
2. Middleware four methods involved
process_request(request, *args, **kwargs)
process_view(self, request, callback, callback_args, callback_kwargs)
process_response(request, response *args, **kwargs) ------process_template_response(self,request,response)
process_exception(self, request, exception)
3. The method of execution order middleware
3. Custom middleware and test its execution flow
We create middleware package under the project directory (and settings.py same level), and a new test module which reads as follows:
from django.utils.deprecation import MiddlewareMixin class ProcessMiddleware1(MiddlewareMixin): def __str__(self): return 'middleware 1' def process_request(self, request): print('%s:\t [%s]' % (self.__str__(), 'process_request')) def process_view(self, *args): print('%s:\t [%s]' % (self.__str__(), 'process_view')) def process_response(self, request, response): print('%s:\t [%s]' % (self.__str__(), 'process_response')) return response class ProcessMiddleware2(MiddlewareMixin): def __str__(self): return 'middleware 2' def process_request(self, request): print('%s:\t [%s]' % (self.__str__(), 'process_request')) def process_view(self, *args): print('%s:\t [%s]' % (self.__str__(), 'process_view')) def process_response(self, request, response): print('%s:\t [%s]' % (self.__str__(), 'process_response')) return response class ProcessMiddleware3(MiddlewareMixin): def __str__(self): return 'middleware 3' def process_request(self, request): print('%s:\t [%s]' % (self.__str__(), 'process_request')) def process_view(self, *args): print('%s:\t [%s]' % (self.__str__(), 'process_view')) def process_response(self, request, response): print('%s:\t [%s]' % (self.__str__(), 'process_response')) return response
operation result: