Flask 銷毀回調(diào)

2021-08-23 18:40 更新

銷毀回調(diào)是是特殊的回調(diào),因?yàn)樗鼈冊(cè)诓煌狞c(diǎn)上執(zhí)行。嚴(yán)格地說(shuō),它們不依賴實(shí)際 的請(qǐng)求處理,因?yàn)樗鼈兿薅ㄔ?nbsp;?RequestContext? 對(duì)象的生命周期。 當(dāng)請(qǐng)求上下文出棧時(shí), ?teardown_request()? 上綁定的函數(shù)會(huì) 被調(diào)用。

這對(duì)于了解請(qǐng)求上下文的壽命是否因?yàn)樵?with 聲明中使用測(cè)試客戶端或在命令行 中使用請(qǐng)求上下文時(shí)被延長(zhǎng)很重要:

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)總是會(huì)被執(zhí)行,即使沒(méi)有請(qǐng)求前回調(diào)執(zhí)行過(guò),或是異常發(fā)生。測(cè)試系 統(tǒng)的特定部分也會(huì)臨時(shí)地在不調(diào)用請(qǐng)求前處理器的情況下創(chuàng)建請(qǐng)求上下文。確保你 寫的請(qǐng)求銷毀處理器不會(huì)報(bào)錯(cuò)。

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)