在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。在django项目的settings模块中,有一个 MIDDLEWARE.
中间件中可以定义如下方法。
process_request(self,request)
process_view(self, request, callback, callback_args, callback_kwargs)
process_template_response(self,request,response)
process_exception(self, request, exception)
process_response(self, request, response)
以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户。
// 撰写中间件
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
class Middle1(MiddlewareMixin):
def process_request(self, request):
print("m1.process_request")
def process_response(self, request, response):
print("m1.process_response")
return response
class Middle2(MiddlewareMixin):
def process_request(self, request):
print("m2.process_request")
def process_response(self, request, response):
print("m2.process_response")
return response
//在settings中注册
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',
"my_middle.Middle1",
"my_middle.Middle2",
]
// 执行结果
//m1.process_request
//m2.process_request
//执行视图函数
//m2.process_response
//m1.process_response