Django之中间件
中间件
什么是Django的中间件
完整django请求的生命周期如果有中间件其中的请求不通过会这样:
所以说中间件其实是在路由系统前就会发生的,在django中是一个类,用其中的process_request函数处理;如果views中函数处理完了以后,则也是要经过中间件来处理,通过相关类中的procee_response处理;其实也可以用process_view对视图函数处理,process_exception对view中函数出现异常处理,process_template_response是在视图中返回的对象中含有render方法才执行。
作用:例如可以对于所有的客户请求,在到达路由系统前,作一些验证的工作。也可以作一些视图函数处理后的后期工作。其实就是对请求的事前事后的统一处理。
关于process_view
process_exception
视图函数中有异常才处理。process_template_response
执行条件:就是views中返回的对象中含有render方法,才执行。
自定义中间件
步骤一、创建文件夹步骤二、写中间件的类
(1)、导入:from django.utils.deprecation import MiddlewareMixin
或者在django.utils.deprecation中把MiddlewareMixin整个类复制过来
(2)、写类,需继承MiddlewareMixin,但注意写以下方法:process_request和process_response、process_view、process_exception、process_template_response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | # from django.utils.deprecation import MiddlewareMixin class 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' ): response = self .process_request(request) response = response or self .get_response(request) if hasattr ( self , 'process_response' ): response = self .process_response(request, response) return response class M1(MiddlewareMixin): def process_request( self , request, * args, * * kwargs): print ( 'm1.process_request' ) def process_response( self , request, response): print ( 'm1.process_response' ) return response # 注意process_response必须有返回值的 class M2(MiddlewareMixin): def process_request( self , request, * args, * * kwargs): print ( 'm2.process_request' ) def process_response( self , request, response): print ( 'm2.process_response' ) return response |
在中间件中实现登陆验证的功能
1 2 3 4 5 6 7 8 | class Auth(MiddlewareMixin): def process_request( self , request, * args, * * kwargs): if request.path_info = = '/login/' : return None # 请求处理也可以return,return None则到下一个中间件,返回其他则交给同一个中间件的process_response处理 if not request.session.get(settings.USER_SESSION_KEY): # 没有建立会话 return redirect( '/login/' ) |
步骤三、在settings.py中加入路径
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」