Flask 销毁回调

销毁回调是是特殊的回调,因为它们在不同的点上执行。严格地说,它们不依赖实际
的请求处理,因为它们限定在 RequestContext 对象的生命周期。
当请求上下文出栈时, teardown_request() 上绑定的函数会
被调用。

这对于了解请求上下文的寿命是否因为在 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
>>>

注意销毁回调总是会被执行,即使没有请求前回调执行过,或是异常发生。测试系
统的特定部分也会临时地在不调用请求前处理器的情况下创建请求上下文。确保你
写的请求销毁处理器不会报错。

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/flask2/21696.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年5月18日
下一篇 2023年5月18日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注