应用上下文和请求上下文怎样分工、怎样退出?
查看完整题解
参考回答
直接回答
应用上下文负责让代码识别当前 Flask 应用,适合用 current_app 和 g。请求上下文额外提供 request 和 session,只与当前请求有关。
讲清原理
通常进入请求时,若当前没有对应的应用上下文,会先推应用上下文再推请求上下文。结束时先清理请求上下文,再清理这一请求推入的应用上下文。手工持有的应用上下文由持有方退出。
例子与易错点
示例在只有应用上下文时读取配置,再进入测试请求读取路径。g 适合存当前上下文的临时数据,用户跨请求状态要有另一个持久位置。
from flask import Flask, current_app, g, has_request_context, request
app = Flask(__name__)
app.config["SERVICE_NAME"] = "catalog"
with app.app_context():
assert not has_request_context()
assert current_app.config["SERVICE_NAME"] == "catalog"
g.cached_count = 3
with app.test_request_context("/items"):
assert current_app.name == app.name and request.path == "/items"
assert not hasattr(g, "cached_count")
print(current_app.config["SERVICE_NAME"], request.path)
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。