标签:options 应用 有一个 back 变量 tin response .com one
一:中间件
中间件:django 中的中间件(middleware),在django中,就是一个类、在请求来和结束后,Django会根据自己的规则在合适的时机执行中间件的相应方法;
应用:对所有请求或一部分请求做批量处理;
在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件;
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) process_response(self,request,response) 必须有返回值 return response process_view(self, request, callback, callback_args, callback_kwargs) process_exception(self,request,exception) process_template_view(self,request,response) 以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照 Django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户;
二:自定义中间件
1、创建中间件类: 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‘
,
‘xiaoxiaoxiao.middleware.auth.RequestExeute‘
,
)
标签:options 应用 有一个 back 变量 tin response .com one
原文地址:http://www.cnblogs.com/nihao123/p/7111326.html