- 在app文件夹里新建middleware.py
- 继承
MiddlewareMixin
, 编写中间件类,重写process_request
、process_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)
- 使用
@MyMiddleware
装饰视图函数
如果要全局使用中间件
需要在settings⽂件中配置⾃定义中间件