python/ Django之中间件

时间:2021-09-03 22:02:38

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、自定义中间件(类)
 from django.utils.deprecation import MiddlewareMixin
class M1(MiddlewareMixin):
def process_request(self,request):
print('M1.process_request') def process_view(self,request,callback,callback_args,callback_kwargs):
print('M1.process_view')
response=callback(request,*callback_args,**callback_kwargs)
return response def process_response(self,request,response):
print('M1.process_response')
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(返回)给用户

python/ Django之中间件

4、中间件执行过程中有return值流程:用户有访问请求,会从中间件最上方的request(接收)一直往下执行,直到那个中间件有return值后在当前的中间值返回给用户,(在1.7左右版本)会直接跳到最后的中间件,然后返回给用户。

python/ Django之中间件

5、view中间件

 from django.utils.deprecation import MiddlewareMixin
class M1(MiddlewareMixin):
def process_request(self,request):
print('M1.process_request') def process_view(self,request,callback,callback_args,callback_kwargs):
print('M1.process_view')
response=callback(request,*callback_args,**callback_kwargs)
return response def process_response(self,request,response):
print('M1.process_response')
return response

view 中间件

python/ Django之中间件