为什么在视图函数之外用 current_app 会报错?g 到底活多久?一个请求里应用上下文什么时候出现、什么时候消失?这篇逐个实测。
current_app.name → RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information. g.x → RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information. url_for → RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information. has_app_context(): False | has_request_context(): False
上一篇:app.run() 的启动过程;下一篇:Flask Request Context。
源码:
1 | app = Flask("demo")
2 | with app.app_context():
3 | print(current_app.name, has_app_context())
4 | print(current_app is app, current_app._get_current_object() is app, type(current_app).__name__)
5 | print(has_app_context())
demo True
False True LocalProxy
Falseg.hits=1 模块变量=1 g 的 id=19280 g.hits=1 模块变量=2 g 的 id=20560 g.hits=1 模块变量=3 g 的 id=19200
appcontext_pushed → request_started → before_request → 视图函数 → after_request → request_finished → teardown_request(exc=None) → teardown_appcontext(exc=None) → appcontext_popped
GET /boom → 500; ['teardown_appcontext 收到:ValueError'] test_request_context 内:has_app_context = True , has_request_context = True , request.path = /x app_context 内:has_app_context = True , has_request_context = False 在应用上下文里访问 request.path → Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to a
['outer', 'inner', 'outer']
flask --app cliapp hello → has_app_context=True current_app.name=cliapp
test_cli_runner: has_app_context=True current_app.name=cliapp
手动调用函数(没有 flask 命令): RuntimeError There is no active click context.