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

相关推荐
m0_748839495 分钟前
CSS如何实现元素平滑滚动_使用scroll-behavior属性设置
jvm·数据库·python
Victoria.a19 分钟前
python基础语法
开发语言·python
xiaotao1311 小时前
01-编程基础与数学基石: Python核心数据结构完全指南
数据结构·人工智能·windows·python
青苔猿猿1 小时前
【1】JupyterLab安装
python·jupyter
xiaoyaohou111 小时前
023、数据增强改进(二):自适应数据增强与AutoAugment策略
开发语言·python
鬼圣1 小时前
Python 上下文管理器
开发语言·python
努力学习_小白1 小时前
ResNet-50——pytorch版
人工智能·pytorch·python
战族狼魂2 小时前
基于LibreOffice +python 实现一个小型销售管理系统的数据库原型教学实验
数据库·python
m0_640309302 小时前
PHP函数怎样适配高可靠性存储硬件_PHP在ZFS RAIDZ环境配置【技巧】
jvm·数据库·python
2402_854808372 小时前
Django REST Framework 中实现用户资料更新的完整实践指南
jvm·数据库·python