Django中的中間件是一個輕量級、底層的插件系統,能夠介入Django的請求和響應處理過程,修改Django的輸入或輸出。中間件的設計爲開發者提供了一種無侵入式的開發方式,加強了Django框架的健壯性,其它的MVC框架也有這個功能,名稱爲IoC。html
Django在中間件中預置了五個方法,這五個方法的區別在於不一樣的階段執行,對輸入或輸出進行干預,方法以下:python
1)初始化:無需任何參數,服務器響應第一個請求的時候調用一次,用於肯定是否啓用當前中間件。django
def __init__(self): pass
2)處理請求前:在每一個請求上,request對象產生以後,url匹配以前調用,返回None或HttpResponse對象(須要使用django自帶的響應對象)瀏覽器
def process_request(self, request): pass
3)處理視圖前:在每一個請求上,url匹配以後,視圖函數調用以前調用,返回None或HttpResponse對象(須要使用django自帶的響應對象)服務器
def process_view(self, request, view_func, *view_args, **view_kwargs): pass
4)處理響應後:視圖函數調用以後,全部響應返回瀏覽器以前被調用,在每一個請求上調用,返回HttpResponse對象(須要使用django自帶的響應對象)框架
def process_response(self, request, response): pass
5)異常處理:當視圖拋出異常時調用,在每一個請求上調用,返回一個HttpResponse對象(須要使用django自帶的響應對象)函數
def process_exception(self, request,exception): pass
中間件是一個獨立的python類,,能夠定義這五個方法中的一個或多個。url
1)在應用booktest/目錄下(該應用和manage.py在同一目錄下)建立middleware.py文件,代碼以下:spa
class my_mid: def __init__(self): print '--------------init' def process_request(self,request): print '--------------request' def process_view(self,request, view_func, *view_args, **view_kwargs): print '--------------view' def process_response(self,request, response): print '--------------response' return response
2)在test5/settings.py文件中,向MIDDLEWARE_CLASSES項中註冊。 插件
3)修改booktest/views.py中視圖index。
def index(request): print '======index======' return render(request,'booktest/index.html')
4)運行服務器,命令行中效果以下圖:
5)刷新頁面,命令行中效果以下圖:
1)在booktest/middleware.py中定義兩個異常類以下:
class exp1: def process_exception(self,request,exception): print '--------------exp1' class exp2: def process_exception(self,request,exception): print '--------------exp2'
2)在test5/settings.py文件中,向MIDDLEWARE_CLASSES項中註冊。
3)修改booktest/views.py中視圖index。
def index(request): print '======index======' raise Exception('自定義異常') return render(request,'booktest/index.html')
總結:若是多個註冊的中間件類中都有process_exception的方法,則先註冊的後執行。