在 Django>=1.10 中编写中间件
从 Django 1.10 开始,中间件类必须在其方法中接受get_response
参数__init__()
并提供__call__()
方法。虽然这可以通过django.utils.deprecation.MiddlewareMixin
在定义中间件类时使用(如W.Perrin 的回答所示)来实现,但在当前支持的 Django 版本中创建基于类的中间件如下所示:
class CustomMiddleware(object):
def __init__(self, get_response):
"""
One-time configuration and initialisation.
"""
self.get_response = get_response
def __call__(self, request):
"""
Code to be executed for each request before the view (and later
middleware) are called.
"""
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
"""
Called just before Django calls the view.
"""
return None
def process_exception(self, request, exception):
"""
Called when a view raises an exception.
"""
return None
def process_template_response(self, request, response):
"""
Called just after the view has finished executing.
"""
return response
process_view()
和是特殊的钩子process_exception()
,process_template_response()
由 Django 在处理中间件时调用,您可以在中间件类中定义。在上面的示例中,实现的钩子不会做任何特别的事情,以确保 Django 将调用下一个中间件来进一步处理响应/请求。
激活中间件
要激活中间件组件,请将其添加到MIDDLEWARE
Django 设置中的列表中。
MIDDLEWARE = [
# Default Django middleware
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Add your custom middleware
'path.to.your.middleware.CustomMiddleware',
]