python runtime_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2025-12-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —
3.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 95% fail

    Unrelated to context propagation.