1.中间件是发生在request和response 之间,都会经过中间键,
上述截图中的中间件都是django中的,我们也可以自己定义一个中间件,我们可以自己写一个类,但是必须继承MiddlewareMixin
需要导入
1 | from django.utils.deprecation import MiddlewareMixin |
1 from django.utils.deprecation import MiddlewareMixin 2 from django.shortcuts import HttpResponse 3 4 class Md1(MiddlewareMixin): 5 6 def process_request(self,request): 7 print("Md1请求") 8 9 def process_response(self,request,response):10 print("Md1返回")11 return response12 13 class Md2(MiddlewareMixin):14 15 def process_request(self,request):16 print("Md2请求")17 #return HttpResponse("Md2中断")18 def process_response(self,request,response):19 print("Md2返回")20 return response
结果:
Md1请求Md2请求view函数...Md2返回Md1返回
如果当请求到达请求2的时候直接不符合条件返回,即return HttpResponse("Md2中断"),程序将把请求直接发给中间件2返回,然后依次返回到请求者,结果如下:
返回Md2中断的页面,后台打印如下:
Md1请求Md2请求Md2返回Md1返回
1 from django.utils.deprecation import MiddlewareMixin 2 from django.shortcuts import redirect,HttpResponse,render 3 class M1(MiddlewareMixin): 4 def process_request(self,request): 5 if request.path in ["/login/","/reg/"]: 6 print(request.META.get("REMOTE_ADDR")) 7 return None 8 if not request.user.is_authenticated: 9 return redirect("/login/")10 11 class M2(MiddlewareMixin):12 def process_request(self,request):13 if "128.0." in request.META.get("REMOTE_ADDR"):14 return redirect("/error/")15 else:16 return None
setting设置
'app01.utils.middleware.M1',