# 运行时错误：在应用上下文之外工作。

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

## 根因

在应用上下文之外访问 Flask 的 current_app、g 或 url_for，通常发生在后台线程或独立脚本中。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   with app.app_context():
    # code that needs current_app
   ```
2. **** (90% 成功率)
   ```
   from flask import current_app
app = create_app()
with app.app_context():
    # use current_app
   ```

## 无效尝试

- **** — Threads don't inherit the context automatically; app objects require an explicit context. (90% 失败率)
- **** — test_request_context returns a context manager; not entering it leaves the context inactive. (85% 失败率)
