python
runtime_error
ai_generated
true
RuntimeError: 在请求上下文之外工作。
RuntimeError: Working outside of request context.
ID: python/flask-request-context-missing
80%修复率
87%置信度
0证据数
2024-04-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
| 3.x | active | — | — | — |
根因分析
在活跃 HTTP 请求之外访问 request、session 或 g(例如在定时任务或未使用 test_request_context 的测试中)。
English
Accessing request, session, or g outside an active HTTP request (e.g., in a scheduled job or test without test_request_context).
解决方案
-
95% 成功率
Capture needed values inside the view: `data = request.get_json()` then pass `data` to the background function.
-
90% 成功率
In tests: `with app.test_request_context('/path', json={...}):` before calling code that reads request.
无效尝试
常见但无效的做法:
-
90% 失败
request is a LocalProxy; module-level access still raises the same error.
-
85% 失败
request.form/args access still throws; caller gets None or wrong data.