俗稱鉤子,用於某個特定的功能python
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. request預處理函數process_request(self,request)nginx
這個方法的調用時機在Django接收到request以後,但仍未解析URL以肯定應當運行的view以前。django
2. view預處理函數process_view(self,request,view,*args,**kwarg)session
這個方法的調用時機在Django執行完request預處理函數並肯定待執行的view以後,但在view函數實際執行以前。app
3. response後處理函數process_response(self,request,response)函數
這個方法的調用時機在Django執行view函數並生成response以後日誌
4. Exception後處理函數process_exception(self,request,exception)csrf
這個方法只有在request處理過程當中出了問題而且view函數拋出了一個未捕獲的異常時纔會被調用。 這個鉤子能夠用來發送錯誤通知,將現場相關信息輸出到日誌文件, 或者甚至嘗試從錯誤中自動恢復。中間件
本身實現中間件需繼承MiddlewareMixin或者本身實現__init__和__call__方法,官方文檔以下blog
class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response
舉個常見的小栗子,記錄訪問者的IP地址(nginx access_log),中間件就能夠完成。
【app.middleware.py】
from datetime import datetime from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class IpLogMiddleware(MiddlewareMixin): """ip記錄""" def process_request(self,request): with open("IpLog.txt","a")as f: # print(request.META["REMOTE_ADDR"]) if request.META.get('HTTP_X_FORWARDED_FOR',None): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] t = datetime.now().strftime("%Y-%m-%d %H:%M:%S") remote_addr = ip+"- -|"+t+"\n" f.write(remote_addr) return None