Flask 銷毀回調(diào)

2021-08-23 18:40 更新

銷毀回調(diào)是是特殊的回調(diào),因為它們在不同的點上執(zhí)行。嚴(yán)格地說,它們不依賴實際 的請求處理,因為它們限定在 ?RequestContext? 對象的生命周期。 當(dāng)請求上下文出棧時, ?teardown_request()? 上綁定的函數(shù)會 被調(diào)用。

這對于了解請求上下文的壽命是否因為在 with 聲明中使用測試客戶端或在命令行 中使用請求上下文時被延長很重要:

with app.test_client() as client:
    resp = client.get('/foo')
    # the teardown functions are still not called at that point
    # even though the response ended and you have the response
    # object in your hand

# only when the code reaches this point the teardown functions
# are called.  Alternatively the same thing happens if another
# request was triggered from the test client

從這些命令行操作中,很容易看出它的行為:

>>> app = Flask(__name__)
>>> @app.teardown_request
... def teardown_request(exception=None):
...     print 'this runs after request'
...
>>> ctx = app.test_request_context()
>>> ctx.push()
>>> ctx.pop()
this runs after request
>>>

注意銷毀回調(diào)總是會被執(zhí)行,即使沒有請求前回調(diào)執(zhí)行過,或是異常發(fā)生。測試系 統(tǒng)的特定部分也會臨時地在不調(diào)用請求前處理器的情況下創(chuàng)建請求上下文。確保你 寫的請求銷毀處理器不會報錯。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號