新聞中心
中間件工廠是一個(gè)可調(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或者它可以寫成一個(gè)類,它的實(shí)例是可調(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 responseDjango 提供的 ?get_response?響應(yīng)可能是實(shí)際視圖(如果這是最后列出的中間件),或者它可能是鏈中的下一個(gè)中間件。不需要知道或關(guān)心當(dāng)前的中間件到底是什么,它只是代表了下一步的內(nèi)容。
以上是一個(gè)輕微的簡化——鏈中最后一個(gè)中間件調(diào)用的 ?get_response?可不是實(shí)際視圖,而是處理程序的包裝方法,它負(fù)責(zé)應(yīng)用 ?view middleware?,調(diào)用具有適當(dāng)URL參數(shù)的視圖,并應(yīng)用 ?template-response? 和 ?exception?中間件。
中間件可以只支持同步Python(默認(rèn)),或異步Python,或者二者都支持。
中間件可以放在 Python 路徑上的任何地方。
__init__(get_response)
中間件工廠必須接受 ?get_response?參數(shù)。還可以初始化中間件的一些全局狀態(tài)。記住兩個(gè)注意事項(xiàng):
- Django僅用 ?
get_response?參數(shù)初始化您的中間件,因此不能定義 ?__init__()? ,因?yàn)樾枰渌麉?shù)。 - 與每個(gè)請求調(diào)用一次的 ?
__call__()? 方法不同,?__init__()? 僅在 Web 服務(wù)器啟動(dòng)時(shí)調(diào)用一次。
標(biāo)記未使用的中間件
在啟動(dòng)時(shí)確定是否應(yīng)該使用一個(gè)中間件有時(shí)是有用的。在這些情況下,您的中間件的 ?__init__()? 方法可能會(huì)引發(fā) ?MiddlewareNotUsed?。Django 將從中間件進(jìn)程中刪除該中間件,并將調(diào)試消息記錄到 ?django.request? 日志:設(shè)置 ?DEBUG?為 ?True?。
文章題目:創(chuàng)新互聯(lián)Django4.0教程:Django4.0 中間件-編寫自己的中間件
文章起源:http://www.5511xx.com/article/djepeej.html


咨詢
建站咨詢
