销毁回调是是特殊的回调,因为它们在不同的点上执行。严格地说,它们不依赖实际 的请求处理,因为它们限定在 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
>>>
注意销毁回调总是会被执行,即使没有请求前回调执行过,或是异常发生。测试系 统的特定部分也会临时地在不调用请求前处理器的情况下创建请求上下文。确保你 写的请求销毁处理器不会报错。
Django也提供允许在代码中完全控制数据库的API。手动指定数据库分配将优先于路由分配的数据库。手动为查询集选择数据库你可以在...
在Django项目中,一个常见需求是获取最终形式的URL,比如用于嵌入生成的内容中(视图和资源网址,给用户展示网址等)或用户服务...
所有 Django 支持的数据库后端都支持迁移,还有些支持表修改(通过 SchemaEditor 类实现)的第三方后端也支持。然而,有些数据库...
除前面说的基础请求/响应中间件模式外,你可以给基于类的中间件添加三种其他特殊方法:process_view()process_view(request, vie...
该会话目录在使用 JSONSerializer 时接受任何 json 序列化值或者当使用 PickleSerializer 时接受任何 picklable Pyt...
默认情况下,Django 为每个模型类添加了一个名为 objects 的 Manager。不过,若你想将 objects 用作字段名,或想使...
Java Swing教程 -Java Swing BorderLayoutBorderLayout将容器的空间分为五个区域:北,南,东,西和中心。BorderLayout将容器的空...
Java Swing教程 -Java Swing JColorChooser方法...以下代码使用JColorChooser选择一种颜色,并在标准输出上打印一条消息:import ...
Java Swing教程 -Java Swing颜色显示垂直工具栏...我们可以使用它的RGB(红,绿,和蓝色)组分。我们可以使用它的RGB(红,绿,和蓝...
Java Swing教程 -Java Swing JButtonJButton也称为按钮。用户按下或单击JButton以执行操作。创建JButtonJButton可以显示文本和图...