20 Django组件之中间件
中间件语法
自定义中间件,继承于MiddlewareMixin
from django.utils.deprecation import MiddlewareMixin class CustomerMiddleware(MiddlewareMixin): def process_request(self,request): print(request.get_host()) print("CustomerMiddleware process_request.....")
在setting的MIDDLEWARE中注册新的中间件
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', 'app.my_middleware.CustomerMiddleware' ]
定义有request和response的中间件。request不用反回执,response一定要有返回值。request有返回HTTPResponse后将会话进行拦截,直接交给自己的response返回给浏览器。
请求执行request中方法,返回时执行response中的方法
class CustomerMiddleware2(MiddlewareMixin): def process_request(self,request): print(request.get_host()) print("CustomerMiddleware process_request.....") def process_response(self,request,response): print("CustomerMiddleware2 response.....") #response必须有返回值 return response
process_view()
class CustomerMiddleware3(MiddlewareMixin): def process_request(self,request): print(request.get_host()) print("CustomerMiddleware process_request.....") def process_response(self,request,response): print("CustomerMiddleware2 response.....") #response必须有返回值 return response def process_view(self,request,callback,callback_args,callback_kwargs): #这里callback就是对应视图函数 #这里不要返回HTTPResponse,返回就不会朝下继续执行,直接返回向上执行response print("CustomerMiddleware3 view")
process_exception()
在代码正常执行的情况下不会被执行,只要查找到一个HTTPResponse对象,即返回
class CustomerMiddleware3(MiddlewareMixin): def process_request(self,request): print(request.get_host()) print("CustomerMiddleware process_request.....") def process_response(self,request,response): print("CustomerMiddleware2 response.....") #response必须有返回值 return response def process_view(self,request,callback,callback_args,callback_kwargs): #这里callback就是对应视图函数 #这里不要返回HTTPResponse,返回就不会朝下继续执行,直接返回向上执行response print("CustomerMiddleware3 view") def process_exception(self,request,response,exception): #exception为视图函数中的错误信息 #返回错误的HTTPResponse对象,有一个exception返回即返回,不会一级一级返回 pass
中间件应用案例
- 做ip访问频率限制
- 访问视图检测是不是有session验证,有则放行,没有则返回login页面,避免多个视图添加login装饰器
大量需要验证,则通过中间件实现验证,相反则通过添加装饰器来完成
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import redirect from userauth import settings class AuthMiddleware(MiddlewareMixin): def process_request(self,request): white_list=settings.WHITE_LIST if request.path in white_list: return None#访问白名单路由直接返回None if not request.user.is_authenticated: #没有通过认证则调转到主页 return redirect('/login/')