W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
中間件工廠是一個可調(diào)用的程序,它接受 ?get_response
?可調(diào)用并返回中間件。中間件是可調(diào)用的,它接受請求并返回響應(yīng),就像視圖一樣。
中間件可以被寫成這樣的函數(shù):
def simple_middleware(get_response):
# One-time configuration and initialization.
def middleware(request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
return middleware
或者它可以寫成一個類,它的實例是可調(diào)用的,如下:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
Django 提供的 ?get_response
?響應(yīng)可能是實際視圖(如果這是最后列出的中間件),或者它可能是鏈中的下一個中間件。不需要知道或關(guān)心當(dāng)前的中間件到底是什么,它只是代表了下一步的內(nèi)容。
以上是一個輕微的簡化——鏈中最后一個中間件調(diào)用的 ?get_response
?可不是實際視圖,而是處理程序的包裝方法,它負責(zé)應(yīng)用 ?view middleware
?,調(diào)用具有適當(dāng)URL參數(shù)的視圖,并應(yīng)用 ?template-response
? 和 ?exception
?中間件。
中間件可以只支持同步Python(默認),或異步Python,或者二者都支持。
中間件可以放在 Python 路徑上的任何地方。
中間件工廠必須接受 ?get_response
?參數(shù)。還可以初始化中間件的一些全局狀態(tài)。記住兩個注意事項:
get_response
?參數(shù)初始化您的中間件,因此不能定義 ?__init__()
? ,因為需要其他參數(shù)。__call__()
? 方法不同,?__init__()
? 僅在 Web 服務(wù)器啟動時調(diào)用一次。在啟動時確定是否應(yīng)該使用一個中間件有時是有用的。在這些情況下,您的中間件的 ?__init__()
? 方法可能會引發(fā) ?MiddlewareNotUsed
?。Django 將從中間件進程中刪除該中間件,并將調(diào)試消息記錄到 ?django.request
? 日志:設(shè)置 ?DEBUG
?為 ?True
?。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: