python
runtime_error
ai_generated
true
RuntimeError: 在请求上下文之外工作。
RuntimeError: Working outside of request context.
ID: python/flask-working-outside-request-context
80%修复率
88%置信度
0证据数
2024-03-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
| 3.x | active | — | — | — |
根因分析
在后台线程、Celery任务或CLI命令中访问request、session或g全局变量,但未激活Flask请求上下文。
English
Accessing request, session, or g globals from a background thread, Celery task, or CLI command without an active Flask request context.
解决方案
-
85% 成功率
with app.test_request_context('/path', method='POST'):\n do_work() -
95% 成功率
def task(user_id, payload): ...\nuser_id = request.headers.get('X-User-Id')\ntask.delay(user_id, request.json)
无效尝试
常见但无效的做法:
-
70% 失败
app_context does not push a request context; request, session, and g still raise RuntimeError.
-
90% 失败
This only affects exception propagation, not context availability.