知識點
- 概念
- 使用場景
- 中間件如何發(fā)生作用
- 自定義中間件
中間件概念
中間件是嵌入 django 的 request/response 處理過程的一套鉤子框架次慢。它是一個輕量級的底層嵌入系統(tǒng)翻斟,可以對 django 的輸入輸出做整體的修改。
使用場景
如果你想修改請求憔恳,例如被傳送到view中的HttpRequest對象。 或者你想修改view返回的HttpResponse對象读第,這些都可以通過中間件來實現(xiàn)昧诱。
可能你還想在view執(zhí)行之前做一些操作畔塔,這種情況就可以用 middleware來實現(xiàn)潭辈。
比如我們寫一個判斷瀏覽器來源,是pc還是手機澈吨,這里手機我們采用iphone把敢,因為暫時沒有其他設(shè)備。我們有不想把這個邏輯加到視圖函數(shù)里谅辣,想作為一個通用服務(wù)修赞,作為一個可插拔的組件被使用,最好的方法就是實現(xiàn)為中間件。
中間件作用流程
Django中間件必須是一個類柏副,不需要繼承任何類勾邦,并實現(xiàn)四個接口:
- process_request(self, request)該方法在請求到來的時候調(diào)用。
- process_view(self ,request, fnc , arg ,kwarg)在本次將要執(zhí)行的View函數(shù)被調(diào)用前調(diào)用本函數(shù)割择。
- process_response(self,request,response)在執(zhí)行完View函數(shù)準(zhǔn)備將響應(yīng)發(fā)到客戶端前被執(zhí)行眷篇。
- process_exception(self,request, exception). View函數(shù)在拋出異常時該函數(shù)被調(diào)用,得到的exception參數(shù)是實際上拋出的異常實例荔泳。通過此方法可以進(jìn)行很好的錯誤控制蕉饼,提供友好的用戶界面。
中間件如何發(fā)生作用
要激活中間件玛歌,需要把它添加到Django 配置文件中的MIDDLEWARE_CLASSES 元組中昧港。
參考文檔
實驗操作
獲取當(dāng)前訪問的客戶端系統(tǒng)信息
【middleware.py】
class CheckSoureMiddware(object):
def process_request(self, request):
from_source = request.META['HTTP_USER_AGENT']
print('from_source ',from_source)
if 'iPhone' in from_source:
request.session['from_source'] = 'iphone'
else:
request.session['from_source'] = 'pc'
def process_response(self, request, response):
res = 'hehe'
print(res)
return HttpResponse(res)
【views.py】
from django.shortcuts import render,HttpResponse
# Create your views here.
def index(request):
res = 'hi, friend! where a u from?'
from_source = request.session.get('from_source', 'unkown')
res = 'hi, friend! u come from %s' %from_source
return HttpResponse(res)
【settings.py】
MIDDLEWARE_CLASSES = [
'example.middleware.CheckSoureMiddware',
]
獲取當(dāng)前訪問的客戶端的IP
【middleware.py】
from django.http import HttpResponse
class ForbidSomeIpMiddleware(object):
def process_request(self, request):
allow_ip = ['127.0.0.1',]
ip = request.META['REMOTE_ADDR']
print('ip ', ip)
if ip in allow_ip:
print('ip not allowed')
return HttpResponse('ip not allowed')
def process_response(self, request, response):
res = 'haha'
print(res)
return HttpResponse(res)
【settings.py】
MIDDLEWARE_CLASSES = [
'example.middleware.ForbidSomeIpMiddleware',
]
結(jié)論
先注冊的中間件先被調(diào)用(可以使用process_response來查看)