django之中間件的配置使用

首先了解下在django中請求處理的過程:html

瀏覽器發起請求 --》 匹配url成功 --》運行view視圖函數 --》 調用html模板 --》返回給瀏覽器。
python

面向切面編程:就是在一種開發好的框架,上述過程當中,任意箭頭位置打斷正常流程,加入一些干預的處理環節,從而實現更多功能且不影響原來的框架流程。django


根據以上要求,最簡單的方法就是修改django的源代碼,但這樣對通常人來講很是有難度,因此,django在框架設計中,就預留出來了這些處理環節,用戶在使用時,根據實際須要選擇修改或者不修改便可。編程


在django中經過提供了一種面向切面編程的工具就叫中間件;實際上中間件就是一個python的類,有固定的6中方法可實現:vim

(1)_init_:服務器響應第一個請求時調用一次,用於肯定是否啓用當前中間件;瀏覽器

(2)process_request(request):執行視圖前被調用,在每一個請求上調用,返回None或HttpResponse對象;bash

(3)process_view(request, view_func, view_args, view_kwargs):調用視圖前被調用,在每一個請求上調用,返回None或HttpResponse對象;
服務器

(4)process_template_response(request,response):在視圖恰好執行完後被調用,在每一個請求上調用,返回實現了render方法的響應對象;框架

(5)process_response(request,response):全部響應返回瀏覽器以前被調用,在每一個請求上調用,返回HttpResponse對象;ide

(6)process_exception(request,response,exception):當視圖拋出異常時調用,在每一個請求上調用,返回一個HttpResponse對象。


下面顯示各個方法在流程中的位置:

瀏覽器發起請求 --process-request()--》 匹配url成功 --prcess_view()--》運行view視圖函數 --process_template_response()--》 調用html模板 --process_response()--》返回給瀏覽器。


第一次瀏覽器發起請求 --》_init_();

運行view視圖函數時,出現異常 --》 process_exception --》 process_response --》返回瀏覽器。


下面演示中間件的配置使用,環境同上篇django文章。

在應用中定義一個python類,實現中間件:

]# cd py3/django-test1/test5
]# vim bookshop/MyException.py
from django.http import HttpResponse
class MyException():
    def process_exception(request,response,exception):
        return HttpResponse(exception)

在settings.py配置文件中註冊中間件:

]# vim test5/settings.py
MIDDLEWARE_CLASSES = (
    'bookshop.MyException.MyException',
    ...
)

定義視圖,驗證中間件應用:

]# vim bookshop/views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return render(request,'bookshop/index.html')
def myExp(request):
    return HttpResponse('hello_world')

配置url:

]# vim bookshop/urls.py
from django.conf.urls import url
from .  import views
urlpatterns = [
    url(r'^$',views.index),
    url(r'^myexp$',views.myExp),
]


啓動django服務:

]# cd py3/django-test1/test5
]# python manage.py runserver 192.168.255.70:8000


瀏覽器訪問:http://192.168.255.70:8000/myexp

顯示:hello_world


在視圖中,設置一個異常代碼:

]# vim bookshop/views.py
...
def myExp(request):
    a1 = int('abc')
    return HttpResponse('hello_world')


瀏覽器訪問:http://192.168.255.70:8000/myexp

顯示:invalid literal for int() with base 10: 'abc'

相關文章
相關標籤/搜索