中間件是一個(gè)鉤子框架,它們可以介入 Django 的請(qǐng)求和響應(yīng)處理過程。 它是一個(gè)輕量級(jí)、底層的 插件 系統(tǒng),用于在 全局修改 Django 的輸入或輸出 。
每個(gè)中間件組件負(fù)責(zé)完成某個(gè)特定的功能
這里介紹的中間件方法適用于 Django1.10 以上
相關(guān)文件: django middleware
Django基礎(chǔ)中間件
django.utils.deprecation.pyclass MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response
以上為Django基礎(chǔ)中間件源碼,要習(xí)慣于看源碼,上面的這段代碼并不復(fù)雜,下面我們來一一解釋。
def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__()
熟悉 python 類的都不陌生 __init__ 方法, 這里主要是 一次性配置和初始化
def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response
__call__ 為每個(gè)請(qǐng)求/響應(yīng)執(zhí)行的代碼
self.process_request(request) 為每個(gè)請(qǐng)求到調(diào)用視圖之前的操作,通常可以在這里做一些用戶請(qǐng)求頻率的控制。
self.get_response(request) 為調(diào)用視圖
self.process_response(request, response) 為調(diào)用視圖完成后的操作
自定義中間件
剛才了解了基礎(chǔ)中間件,現(xiàn)在就開始編寫我們自己的中間件。
通常我們回去繼承基礎(chǔ)中間件來實(shí)現(xiàn)自己的功能
from django.utils.deprecation import MiddlewareMixinclass PermissionMiddlewareMixin(MiddlewareMixin): """ django 中間件 """ def process_request(self, request): pass def process_response(self, request, response): return response
如果你要在請(qǐng)求之前做處理,需要定義 process_request() 方法,去實(shí)現(xiàn)相關(guān)功能
如果你要在視圖調(diào)用之后做處理,需要定義 process_response() 方法,去實(shí)現(xiàn)相關(guān)功能
:warning:注意 定義 process_response() 方法一定要 return response
需要將你編寫的中間件添加到 settings 中的 MIDDLEWARE 里
我這里寫了一個(gè)通過中間件限制客戶端請(qǐng)求頻率,有興趣的可以看一下
django中間件客戶端請(qǐng)求頻率限制
通過redis lua腳本對(duì)客戶端IP請(qǐng)求頻率限制
新聞熱點(diǎn)
疑難解答
圖片精選