# RuntimeError: 在应用上下文之外工作（在线程目标函数中抛出）。

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

## 根因

从请求中启动的后台线程尝试访问 current_app 或 db.session，但 Flask 的上下文是线程局部的，不会继承。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   def worker(app, payload):
    with app.app_context():
        ...
threading.Thread(target=worker, args=(current_app._get_current_object(), payload)).start()
   ```
2. **** (90% 成功率)
   ```
   Use Celery with a Flask app factory and `task_context` pattern to inject app context.
   ```

## 无效尝试

- **** — current_app is a LocalProxy; accessing it in the thread still raises. (90% 失败率)
- **** — Unrelated to context propagation. (95% 失败率)
