标签:site __call view class min -- cut wmi messages
一.django生命周期:用户通过一个个的中间件,访问路由映射,通过views函数,再同样的路径返回(如上图)
二.中间件写法:
1.新建mid模块,模块下新建middle.py ------------middle.py from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class MYMiddlewareMixin(MiddlewareMixin): #自定义类,用时拷贝即可 def __init__(self, get_response=None): self.get_response = get_response super().__init__() def __call__(self, request): response = None if hasattr(self, ‘process_request‘): #判断类中是否有process_request(),名字可以更改 response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, ‘process_response‘): response = self.process_response(request, response) return response class GYK(MYMiddlewareMixin): def process_request(self,request): #1请求 print("11") # return HttpResponse("你大爷") #如果有return,不会执行下一个中间件 def process_response(self,request,response): #4返回 print("22") return response class BYK(MYMiddlewareMixin): def process_request(self,request): #2 print("33") def process_response(self,request,response): #3 print("44") return response
-------------settings.py(csrf也是中间件)
ps:以下中间件按照顺序执行
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‘,
"app01.mid.middle.GYK",
"app01.mid.middle.BYK",
]
-------------urls.py
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path("middle/",views.middle),
]
---------------views.py
def middle(req):
return HttpResponse("Test")
ps:因为中间件按照顺序执行,所以打印结果为:
1.11
2.33
3.44
4.22
一般的执行顺序:1.先执行请求函数process_request 2.执行views函数 3.再执行回应函数process_response。views.py函数中返回“Test”,传给BYK中的response,再传给GYK中的response,再返回给客户。
二般的执行顺序:如果A中间件的process_request()有return HttpResponse("xxx"),不会执行下一个中间件,也不会执行到views.py函数,只执行A中间件,返回给用户xxx
只有将自定义的中间件添加进settings.py中才能执行
标签:site __call view class min -- cut wmi messages
原文地址:https://www.cnblogs.com/gaoyukun/p/9205409.html