随笔 - 105  文章 - 0  评论 - 0  阅读 - 40744

Django之中间件

中间件

什么是Django的中间件

完整django请求的生命周期

如果有中间件其中的请求不通过会这样:

所以说中间件其实是在路由系统前就会发生的,在django中是一个类,用其中的process_request函数处理;如果views中函数处理完了以后,则也是要经过中间件来处理,通过相关类中的procee_response处理;其实也可以用process_view对视图函数处理,process_exception对view中函数出现异常处理,process_template_response是在视图中返回的对象中含有render方法才执行。

作用:例如可以对于所有的客户请求,在到达路由系统前,作一些验证的工作。也可以作一些视图函数处理后的后期工作。其实就是对请求的事前事后的统一处理。

关于process_view

![](https://img2018.cnblogs.com/blog/1503064/202001/1503064-20200113232736819-1983411496.png)

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中加入路径

posted on   Treelight  阅读(134)  评论(0编辑  收藏  举报
编辑推荐:
· 从 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 热点速览」
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示