当前位置: 首页 > news >正文

django 中间件

在主目录下创建了一个middleware.py的文件;

不使用中间件定义的方法

get_response 会跳过默写中间件的方法

import logginglogger = logging.getLogger(__name__)class CountRequestMiddleware():def __init__(self, get_response):self.get_response = get_responseself.count_request = 0self.count_exceptions = 0def __call__(self,request, *args, **kwargs):self.count_request += 1logger.info(f"Handle {self.count_request} requests so far")return self.get_response(request)

使用中间件定义的方法 

中间件中可以定义5个方法,分别是:

  1. process_request(self,request) : 执行视图之前被调用,在每个请求上调用,返回None或HttpResponse对象

  2. process_view(self, request, callback, callback_args, callback_kwargs): 调用视图之前被调用,在每个请求上调用,返回None或HttpResponse对象

  3. process_template_response(self,request,response): 在视图刚好执行完毕之后被调用,在每个请求上调用,返回实现了render方法的响应对象

  4. process_exception(self, request, exception) 当视图抛出异常时调用,在每个请求上调用,返回一个HttpResponse对象

  5. process_response(self, request, response) 所有响应返回浏览器之前被调用,在每个请求上调用,返回HttpResponse对象

import logging
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponselogger = logging.getLogger(__name__)class CountRequestMiddleware(MiddlewareMixin):def process_request(self, request):print("my process_request")print(f"[{request.method}] {request.path} - 进入中间件")def process_view(self, request, callback, callback_args, callback_kwargs):print("my process_view")return Nonedef process_template_response(self, request, response):print("my process_template_response")return responsedef process_response(self, request, response):print("my process_response")print(f"[{response.status_code}] {request.path} - 离开中间件")return responsedef process_exception(exception):print("my process_template_response")return HttpResponse(exception)

注册中间件:

将自定义的中间件类注册到settings.py中间件中,把自定义的中间件的类添加到MIDLEWARE的列表当中

可参照 Django 中间件开发完全指南_中间件如何开发-CSDN博客

Django中中间件学习之如何使用自定义中间件-腾讯云开发者社区-腾讯云

相关文章:

  • wordpress网站静态化国外网站搭建
  • 做网站需要花钱吗女排联赛最新排行榜
  • 衡水有做网站的吗临沂网站建设优化
  • 网站建设推广公众号制作推广青岛做网站设计哪里有
  • 游戏网站制作公司全网推广
  • 郑州网络营销顾问郑州seo代理外包
  • Android14音频子系统-Linux音频子系统ASoC-ALSA
  • python网络自动化-数据格式与数据建模语言
  • PDF处理控件Spire.PDF系列教程:Python中快速提取PDF文本、表格、图像及文档信息
  • TensorFlow Lite (TFLite) 和 PyTorch Mobile模型介绍1
  • AingDesk开源免费的本地 AI 模型管理工具(搭建和调用MCP)
  • Lychee路径遍历漏洞导致敏感文件泄露(CVE-2025-50202)
  • AList的开源替代:OpenList
  • 生产环境的项目中java是如何定义,如何使用,如何关闭线程池的
  • OpenCV图像旋转:单点旋转与图片旋转
  • dify中MCP SSE/StreamableHTTP与mcp server插件的区别
  • TDengine 的 CASE WHEN 语法技术详细
  • XC7K70T-3FBG676E Xilinx FPGA Kintex-7 AMD
  • OpenHarmony构建脚本build.sh解析
  • 深入剖析:Spring Boot系统开发的高效之道
  • 数字:数学里面的右手定则指的是什么?
  • 基于SSM框架+mysql实现的监考安排管理系统[含源码+数据库+项目开发技术手册]
  • 【ArcGIS】水资源单项评价
  • 企业级应用中的编程风格深度剖析与实践指南
  • 3 大语言模型预训练数据-3.2 数据处理-3.2.2 冗余去除——3.后缀数组(Suffix Array)在大模型数据去重中的原理与实战
  • ivx创建一个测试小案例