Django中间件
中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出
用户----中间件—url—视图
在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',
'user.middle_wares.TestMiddleWare' # 中间件
]
中间件可以定义的四个方法:
process_request(self,request)
process_view(self, request, view_func, view_args, view_kwargs)
process_exception(self, request, exception)
process_response(self, request, response)
中间件自己定义的方法:
from django.middleware.common import MiddlewareMixin
from django.http import HttpResponse
from . import models
class TestMiddleWare(MiddlewareMixin):
def process_request(self,request):
#请求来了之后先到这里,根据需求进行请求的分发
print('中间件-请求之前')
pass
def process_response(self,request,response):
# 拦截返回的
print('中间件-response')
return response
def process_exception(self,request,exception):
#拦截异常的
print('出异常了')
return HttpResponse('异常了')