python
runtime_error
ai_generated
true
RuntimeError: Working outside of application context. (raised in threading.Thread target)
ID: python/flask-app-context-in-thread
80%Fix Rate
88%Confidence
0Evidence
2025-12-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
def worker(app, payload): with app.app_context(): ... threading.Thread(target=worker, args=(current_app._get_current_object(), payload)).start() -
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:
-
90% fail
current_app is a LocalProxy; accessing it in the thread still raises.
-
95% fail
Unrelated to context propagation.