一:中間件python
中間件:django 中的中間件(middleware),在django中,就是一個類、在請求來和結束後,Django會根據本身的規則在合適的時機執行中間件的相應方法;django
應用:對全部請求或一部分請求作批量處理;
在django項目的settings模塊中,有一個 MIDDLEWARE_CLASSES 變量,其中每個元素就是一箇中間件;session
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', ]
一、中間件能夠定義的五個方法:ide
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對象,則直接將該對象返回給用戶;
二:自定義中間件spa
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
二、註冊中間件
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'
,
)