定义中间件
from django.utils.deprecation import MiddlewareMixin class M1(MiddlewareMixin): ''' 中间件1 ''' def process_request(self,request): print('M1进来了') def process_response(self,request,response): print('M1走了') return response class M2(MiddlewareMixin): ''' 中间件1 ''' def process_request(self,request): print('M2进来了') def process_response(self,request,response): print('M2走了') return response
应用中间件
需要在setting.py文件中注册中间件
中间件实现登录的校验:
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, redirect class M1(MiddlewareMixin): ''' 中间件1 ''' def process_request(self,request): # 排除特定的URL # request.path_info # 获取用户当前请求的URL if request.path_info =='/account/login/': # 如果请求的URL为登录的URl:/admin/login/,就继续往下走 return # 读取当前访问的用户的session信息。能读取到,说明已经登录过,就可以继续往后走 info_dict =request.session.get("info") if info_dict: return # 没有登录过 return redirect('/account/login/')
标签:return,process,中间件,self,request,response From: https://www.cnblogs.com/xujunhui/p/17449040.html