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

相关推荐
喵手6 分钟前
Python爬虫零基础入门【第九章:实战项目教学·第8节】限速器进阶:令牌桶 + 动态降速(429/5xx)!
爬虫·python·令牌桶·python爬虫工程化实战·python爬虫零基础入门·限速器·动态降速
深度学习lover11 分钟前
<项目代码>yolo毛毛虫识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·毛毛虫识别
喵手11 分钟前
Python爬虫零基础入门【第九章:实战项目教学·第3节】通用清洗工具包:日期/金额/单位/空值(可复用)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·通用清洗工具包·爬虫实战项目
b20772112 分钟前
Flutter for OpenHarmony 身体健康状况记录App实战 - 体重趋势实现
python·flutter·harmonyos
喵手15 分钟前
Python爬虫零基础入门【第九章:实战项目教学·第4节】质量报告自动生成:缺失率/重复率/异常值 TopN!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·实战项目教学·质量报告自动生成
b20772116 分钟前
Flutter for OpenHarmony 身体健康状况记录App实战 - 个人中心实现
android·java·python·flutter·harmonyos
喵手17 分钟前
Python爬虫零基础入门【第九章:实战项目教学·第7节】增量采集:last_time / last_id 两种策略各做一遍!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·增量采集·策略采集
子午28 分钟前
【2026计算机毕设】水果识别分类系统~python+深度学习+人工智能+算法模型+TensorFlow
人工智能·python·深度学习
No0d1es33 分钟前
2023年NOC大赛创客智慧编程赛项Python复赛模拟题(二)
python·青少年编程·noc·复赛·模拟题
SmartRadio37 分钟前
ESP32-S3实现KVM远控+云玩功能 完整方案
运维·python·计算机外设·esp32·kvm·云玩