django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
在django项目的settings模块中,有一个 MIDDLEWARE变量,其中每一个元素就是一个中间件(也就是一个中间件模块的一个类),如下。
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', ]
自定义中间件
1、定义中间件模块,在中间件模块里定义中间件类
process_request(self, request)有请求时执行
request参数接收请求信息对象
process_view(self, request, callback, callback_args, callback_kwargs)逻辑处理之前执行
process_exception(self, request, exception)出错时执行
exception参数接收错误信息
process_response(self, request, response)响应后执行,无论是否出错
response参数接收html页面对象,立面包含响应码
#!/usr/bin/env python #coding:utf-8 from django.utils.deprecation import MiddlewareMixin from django.shortcuts import render class zhongjianjian(MiddlewareMixin): def process_request(self, request): print('有请求时执行') # print(request.META) #请求对象内容 #在这里可以做ip访问拦截器 def process_view(self, request, callback, callback_args, callback_kwargs): print('逻辑处理之前执行') def process_exception(self, request, exception): print('出错时执行') # return render(request, 'app1/cuowu.html') print(exception) #做程序出错时处理 def process_response(self, request, response): print('响应后执行,无论是否出错') return response
2、将中间件模块里的类路径注册到MIDDLEWARE列表里
#中间件 MIDDLEWARE = [ 'app1.chajian.zhong_jian_jian.zhongjianjian', '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', ]
中间件工作流程
#中间件 MIDDLEWARE = [ 'app1.chajian.zhong_jian_jian.zhongjianjian', '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', ]
如果出错流程