# RuntimeError: 在请求上下文之外工作。

- **ID:** `python/flask-working-outside-request-context`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在后台线程、Celery任务或CLI命令中访问request、session或g全局变量，但未激活Flask请求上下文。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 2.x | active | — | — |
| 3.x | active | — | — |

## 解决方案

1. **** (85% 成功率)
   ```
   with app.test_request_context('/path', method='POST'):\n    do_work()
   ```
2. **** (95% 成功率)
   ```
   def task(user_id, payload): ...\nuser_id = request.headers.get('X-User-Id')\ntask.delay(user_id, request.json)
   ```

## 无效尝试

- **** — app_context does not push a request context; request, session, and g still raise RuntimeError. (70% 失败率)
- **** — This only affects exception propagation, not context availability. (90% 失败率)
