Categories: Flask 中文教程

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
>>>

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

唐伯虎点蚊香

前端小白,想各位学习!

Share
Published by
唐伯虎点蚊香

Recent Posts

vue:页面注入js修改input值

一般会直接这样写: let z…

7 小时 ago

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago