中间件字符串导入方式
- 在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。
- 在django项目的settings模块中,有一个 MIDDLEWARE变量,其中每一个元素就是一个中间件。
from django.middleware.common import CommonMiddleware
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',
'wupeiqi.middleware.auth.Authentication',
]
- 与mange.py在同一目录下的文件夹 wupeiqi/middleware下的auth.py文件中的Authentication类中间件中可以定义如下5个方法:
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)
自定义中间件
1. 创建中间件类
从项目目录下面 m1/middleware/auth.python
class RequestExeute(object):
def process_request(self,request):
pass
def process_view(self, request, callback, callback_args, callback_kwargs):
i =1
pass
def process_exception(self, request, exception):
pass
def process_response(self, request, response):
return response
2. 注册中间件
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'm1.middleware.auth.RequestExeute',
)
3. 中间件的常见应用
- 请求日志
- 用户登录认证
- 各种跳转
- 防火墙
网友评论