python
context_error
ai_generated
true
RuntimeError: Working outside of application context
ID: python/flask-working-outside-context
92%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Flask operation requires app context. Accessing current_app, g, or db outside of a request/CLI.
genericWorkarounds
-
95% success Use with app.app_context(): to push an application context
with app.app_context(): db.create_all()Sources: https://flask.palletsprojects.com/en/3.0.x/appcontext/
-
90% success In tests, use app.test_client() or app.test_request_context()
with app.test_request_context(): ...
Sources: https://flask.palletsprojects.com/en/3.0.x/testing/
Dead Ends
Common approaches that don't work:
-
Import the app instance directly
65% fail
Creates circular imports and bypasses Flask's context-local design
-
Set global variables instead of using g/current_app
80% fail
Breaks in multi-threaded/multi-worker deployments
Error Chain
Frequently confused with: