python/ Django之中间件
一、中间件
中间件共分为:
(1)process_request(self,request)
(2)process_view(self, request, callback, callback_args, callback_kwargs)
(3)process_template_response(self,request,response)
(4)process_exception(self, request, exception)
(5)process_response(self, request, response)
1、所谓的中间件,就是存在socket和视图函数中间的一种相当于过滤的机构。
1、自定义中间件(类)
1 from django.utils.deprecation import MiddlewareMixin 2 class M1(MiddlewareMixin): 3 def process_request(self,request): 4 print('M1.process_request') 5 6 def process_view(self,request,callback,callback_args,callback_kwargs): 7 print('M1.process_view') 8 response=callback(request,*callback_args,**callback_kwargs) 9 return response 10 11 def process_response(self,request,response): 12 print('M1.process_response') 13 return response
2、注册中间件 找到settings.py中MIDDLEWARE
2、如下列代码
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'md.M1', 'md.M2', ]
3、中间件执行流程:
用户有访问请求,会从中间件最上方的request(接收)一直往下执行,最后到视图函数然后再由中间件从下往上的response(返回)给用户
4、中间件执行过程中有return值流程:用户有访问请求,会从中间件最上方的request(接收)一直往下执行,直到那个中间件有return值后在当前的中间值返回给用户,(在1.7左右版本)会直接跳到最后的中间件,然后返回给用户。
5、view中间件
1 from django.utils.deprecation import MiddlewareMixin 2 class M1(MiddlewareMixin): 3 def process_request(self,request): 4 print('M1.process_request') 5 6 def process_view(self,request,callback,callback_args,callback_kwargs): 7 print('M1.process_view') 8 response=callback(request,*callback_args,**callback_kwargs) 9 return response 10 11 def process_response(self,request,response): 12 print('M1.process_response') 13 return response