# RuntimeError：在应用程序上下文之外工作。

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

## 根因

在没有活动应用程序上下文的情况下访问 Flask 的 current_app 或其他上下文局部代理，常见于后台线程、CLI 脚本或 Celery 任务中。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   from flask import current_app
with app.app_context():
    print(current_app.config['SECRET_KEY'])
   ```
2. **** (90% 成功率)
   ```
   def worker():
    with app.app_context():
        # do work
        pass
   ```

## 无效尝试

- **** — test_request_context is meant for tests and doesn't push a proper app context for production use, leading to subtle bugs. (55% 失败率)
- **** — This config only affects exception propagation, not context availability. (90% 失败率)
