1. 什么是中间件(Django)?
对Django而言,中间件就是继承自MiddlewareMixin(位于django.utils.deprecation模块下)的类,该类对请求(request)及响应(response)的过程按照规则执行相应的控制方法,达到访问控制,权限管理,请求认证,数据缓存等等效果。
在django2.x中,项目会默认开启以下中间件,通过查看这些中间件的源码可以得知,
基本上这些内置中间件都重写了基类的process_request(request, *args, **kwargs)以及process_response(request, response *args, **kwargs)方法,
中间件(CsrfViewMiddleware等)重写了process_view(self, request, callback, callback_args, callback_kwargs)
视图(views)执行过程中的错误处理则是通过process_exception(self, request, exception)来控制。
2. 中间件所涉及的四种方法
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. 中间件方法的执行顺序
3. 自定义中间件并测试其执行流程
我们在项目目录(与settings.py同级)下创建middleware包, 并新建test模块其内容如下:
from django.utils.deprecation import MiddlewareMixin class ProcessMiddleware1(MiddlewareMixin): def __str__(self): return 'middleware 1' def process_request(self, request): print('%s: [%s]' % (self.__str__(), 'process_request')) def process_view(self, *args): print('%s: [%s]' % (self.__str__(), 'process_view')) def process_response(self, request, response): print('%s: [%s]' % (self.__str__(), 'process_response')) return response class ProcessMiddleware2(MiddlewareMixin): def __str__(self): return 'middleware 2' def process_request(self, request): print('%s: [%s]' % (self.__str__(), 'process_request')) def process_view(self, *args): print('%s: [%s]' % (self.__str__(), 'process_view')) def process_response(self, request, response): print('%s: [%s]' % (self.__str__(), 'process_response')) return response class ProcessMiddleware3(MiddlewareMixin): def __str__(self): return 'middleware 3' def process_request(self, request): print('%s: [%s]' % (self.__str__(), 'process_request')) def process_view(self, *args): print('%s: [%s]' % (self.__str__(), 'process_view')) def process_response(self, request, response): print('%s: [%s]' % (self.__str__(), 'process_response')) return response
运行结果: