1、中間件概念 html
django 自帶函數能夠在幾個環節調節收到請求、處理請求、處理異常、以及發送請求。django
看這裏給的連接好了,這是一個大佬的講django中間件的博客,很是清楚:https://www.cnblogs.com/zhaof/p/6281541.html瀏覽器
接下,我講講我使用的代碼:函數
2、中間件示例url
一、先在應用下的目錄(如上圖),建立中間件文件「MyException.py」, 輸入如下內容spa
from django.http import HttpResponse #a middleware class MyException(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_exception(request, response, exception): return HttpResponse("This is an exception!")
二、在主應用文件的Setting.py 的 "MIDDLEWARE " 中加入上面的文件名(得包括文件路徑):booktest.MyException.MyExceptioncode
三、在應用的 view 文件中加入,這是一個會拋出異常的邏輯:htm
#create the middleware def myExp(request): a1 = int('abc') return HttpResponse('hello')
四、在應用的 url 文件中加入:中間件
url(r'^myexp/$', views.myExp)
3、運行應用,而後在瀏覽器訪問該地址:http://127.0.0.1:8000/booktest/myexp/blog
因爲拋出異常,會獲得如圖
這就是上面中間件文件定義的時候,拋出的異常的信息。
完成了。