Flask-SQLAlchemy 3: db.create_all() in wsgi.py or a script raises 'RuntimeError: Working outside of application context.'
Fix: wrap startup and script database work in an app context:
app = create_app()
with app.app_context():
db.create_all() # or seed data, db.session.execute(...)For one-off tasks, a Flask CLI command (@app.cli.command(), run as flask --app wsgi seed) pushes the context for you.
Cause: with the app factory pattern, db = SQLAlchemy() isn't bound to an app. Flask-SQLAlchemy 3.x finds the engine through current_app, so any session or create_all call outside a request fails with: RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). (reproduced with Flask 3.0.0 + Flask-SQLAlchemy 3.1.1 by calling db.create_all() right after db.init_app(app)).
Background threads and SSE generators hit the same thing once the request has ended. Pass the app object in (app = current_app._get_current_object()) and open with app.app_context(): in the thread. Watch out: pytest-flask pushes a context for every test, so tests can pass even when this is missing.