【Django】中间件实现钩子函数预处理和后处理,局部装饰视图函数

  1. 在app文件夹里新建middleware.py
  2. 继承MiddlewareMixin, 编写中间件类,重写process_requestprocess_response钩子函数
python 复制代码
from django.http import HttpRequest, HttpResponse
from django.utils.decorators import decorator_from_middleware
from django.utils.deprecation import MiddlewareMixin

class MyMiddleware(MiddlewareMixin):
    def __init__(self, get_response=None):
        super().__init__(get_response)
    
    def process_request(self, request: HttpRequest) -> None:
        """视图函数前 钩子函数"""
        ...
        pass
    
    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
        """视图函数后 钩子函数"""
        ...
        return response

# 中间件类包装成装饰器
my_middleware = decorator_from_middleware(MyMiddleware)
  1. 使用@MyMiddleware装饰视图函数

如果要全局使用中间件

需要在settings⽂件中配置⾃定义中间件

相关推荐
deephub8 分钟前
多智能体系统的三种编排模式:Supervisor、Pipeline 与 Swarm
人工智能·python·大语言模型·agent
m0_7381207215 分钟前
渗透测试——pyexpvm靶机详细提权过程(MSF框架,Hydra数据库爆破,SUDO提权)
服务器·网络·数据库·python·sql·web安全
翱翔的苍鹰15 分钟前
LangChain是一个主流的大语言模型(LLM)应用开发框架,核心功能是连接大模型与外部资源/工具。
网络·人工智能·python·深度学习·语言模型
rgb2gray18 分钟前
论文详解 | HDAM:破解 MAUP 的城市出行需求分析新方法,实现关键驱动精准识别
人工智能·python·llm·大语言模型·需求分析·多模态·maup
___波子 Pro Max.20 分钟前
Python容器类型差异操作
python
weixin1997010801623 分钟前
淘宝客商品详情页前端性能优化实战
java·前端·python·性能优化
心歌技术27 分钟前
CPU与GPU排序性能对比分析
python·gpu·性能对比·实验
Zhansiqi28 分钟前
day37英语
python
进击的小头32 分钟前
第7篇:基于传递函数的PI控制器设计
python·算法
七夜zippoe41 分钟前
Python错误追踪终极指南:Sentry集成与深度定制实战
数据库·python·sentry·告警策略·错误追踪