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

- **ID:** `python/flask-runtimeerror-application-context-not-available`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

代码在应用上下文之外尝试访问应用级上下文（如current_app, g），例如在后台线程或第一个请求之前。

## 版本兼容性

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

## 解决方案

1. **Push application context manually** (90% 成功率)
   ```
   with app.app_context():
    # access current_app here
    pass
   ```
2. **Use Flask's before_first_request decorator** (85% 成功率)
   ```
   @app.before_first_request
def setup():
    # setup code here
    pass
   ```

## 无效尝试

- **Using current_app in a module-level variable** — Module-level code runs before app context exists. (80% 失败率)
- **Assuming g is always available** — g is request-specific and only available within request context. (70% 失败率)
