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

相关推荐
敏编程1 小时前
一天一个Python库:virtualenv - 隔离你的Python环境,保持项目整洁
python
喝茶与编码3 小时前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone77393 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户8356290780513 小时前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python
用户962377954484 小时前
🚀 docx2md-picgo:Word 文档图片一键上传图床工具
python·markdown
程序设计实验室1 天前
当人人都能用 AI 写代码时,我为什么选择重回 Django?
django·djangostarter
zone77391 天前
001:简单 RAG 入门
后端·python·面试
F_Quant1 天前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来1 天前
在node项目中执行python脚本
前端·python·node.js
IVEN_1 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv