新聞中心
這里有您想知道的互聯網營銷解決方案
創(chuàng)新互聯Django4.0教程:Django4.0 中間件-編寫自己的中間件
中間件工廠是一個可調用的程序,它接受 ?get_response?可調用并返回中間件。中間件是可調用的,它接受請求并返回響應,就像視圖一樣。

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


咨詢
建站咨詢
