Django middleware (中间件)
关于中间价:
django 中的中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
在django项目的settings中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件
settings.py:
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'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',
]
中间件中可以定义五个方法:
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对象,则直接将该对象返回给用户。
中间件执行过程:
自定义中间件
步骤
1.创建中间件类
Project/middle_ware/middle_print.py
from django.utils.deprecation import MiddlewareMixin
class First(MiddlewareMixin):
def process_request(self, request):
pass
def process_view(self, request, callback, callback_args, callback_kwargs):
pass
def process_exception(self, request, exception):
pass
def process_template_response(self, request, response):
# 当views中返回一个render时执行
pass
def process_response(self, request, response):
return response
2.注册中间件
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'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',
# 自定义中间件
'middle_ware.middle_print.First',
]
自定义中间件完成