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

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

## 根因

在活跃的请求上下文之外尝试使用 Flask 的 request 对象（例如 request.args、request.form），例如在后台线程或应用初始化期间。

## 版本兼容性

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

## 解决方案

1. **Use app.test_request_context() to create a temporary context** (90% 成功率)
   ```
   with app.test_request_context():
    # access request here
    print(request.args)
   ```
2. **Pass request data explicitly to background tasks** (85% 成功率)
   ```
   def background_task(user_id):
    # use passed data, not request
    pass
# In route:
user_id = request.args.get('id')
Thread(target=background_task, args=(user_id,)).start()
   ```

## 无效尝试

- **Using app.request_context() manually without pushing context** — Creates context but doesn't push it, so request is still unavailable. (70% 失败率)
- **Accessing request in a Celery task without context** — Celery tasks run in separate threads, lacking Flask context. (85% 失败率)
