python runtime_error ai_generated true

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

RuntimeError: Working outside of application context. (raised in threading.Thread target)

ID: python/flask-app-context-in-thread

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2025-12-20首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —
3.x active — — —

根因分析

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

English

A background thread spawned from a request tries to access current_app or db.session, but Flask's context is thread-local and not inherited.

generic

解决方案

  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.

无效尝试

常见但无效的做法:

  1. 90% 失败

    current_app is a LocalProxy; accessing it in the thread still raises.

  2. 95% 失败

    Unrelated to context propagation.