MiddlewareMixin
, 编写中间件类,重写process_request
、process_response
钩子函数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⽂件中配置⾃定义中间件