【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⽂件中配置⾃定义中间件

相关推荐
ZC跨境爬虫4 分钟前
海南大学交友平台开发实战 day10(后端向前端输出_前端读取数据全流程联调+日志调试落地)
前端·python·sqlite·html·状态模式
郝学胜-神的一滴15 分钟前
从链表到二叉树:树形结构的入门与核心性质解析
数据结构·c++·python·算法·链表
yongyoudayee29 分钟前
2026中国企业出海CRM:五大平台技术能力对比
后端·python·flask
电商API&Tina31 分钟前
淘宝 / 京东关键词搜索 API 接入与实战用途教程|从 0 到 1 搭建电商选品 / 比价 / 爬虫替代系统
java·开发语言·数据库·c++·python·spring
老wang你好32 分钟前
Python编程入门:变量与数据类型详解
python
lbb 小魔仙1 小时前
Python_PromptEngineering终极指南
开发语言·python
阿荻在肝了1 小时前
Agent实践三:基于Chroma的RAG检索
python·学习·agent
阿Y加油吧1 小时前
单调栈与堆的经典应用:柱状图最大矩形 & 数组第 K 大元素深度解析
开发语言·python
Strugglingler1 小时前
Python学习记录
开发语言·python
Dfreedom.1 小时前
Scikit-learn 全景解读:机器学习的“瑞士军刀”
python·机器学习·scikit-learn