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

相关推荐
山顶夕景11 分钟前
【VLM】结合Python沙箱的以图思辨S1-VL模型
python·大模型·llm·agent·多模态·vlm
和小潘一起学AI17 分钟前
Python导入私有模块(企业级方案)
开发语言·python
2401_8714928529 分钟前
Vue.js计算属性computed依赖追踪与副作用函数effect关联机制
jvm·数据库·python
qq_2837200530 分钟前
本地大模型部署全教程:Python 低成本调用开源 AI 模型
人工智能·python·开源
2401_8822737233 分钟前
SQL如何快速提取分组中最晚时间点数据_结合窗口函数实现
jvm·数据库·python
小何code34 分钟前
【Python零基础入门】第4篇:Python变量与数据类型详解
开发语言·python
卷心菜狗1 小时前
Python进阶--生成器(Generator)
python
2301_814809861 小时前
如何用 cookie 的 HttpOnly 与 Secure 属性防范 XSS 攻击
jvm·数据库·python
李松桃1 小时前
实战:手刃豆瓣电影TOP250
python·爬虫实战·requests·re
m0_515098421 小时前
如何用 Object.keys 与 getOwnPropertyNames 遍历键名
jvm·数据库·python