python runtime_error ai_generated true

RuntimeError: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app'?

ID: python/flask-db-not-initialized

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-16First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Using db.session outside an app context, or the SQLAlchemy extension was never bound to the app via db.init_app(app).

generic

中文

在应用上下文之外使用 db.session,或 SQLAlchemy 扩展从未通过 db.init_app(app) 绑定到应用。

Workarounds

  1. 93% success
    In factory: db.init_app(app); with app.app_context(): db.create_all()
  2. 90% success
    Wrap script code: with app.app_context(): db.session.add(obj); db.session.commit()

Dead Ends

Common approaches that don't work:

  1. 85% fail

    No app context; raises the same error.

  2. 70% fail

    Still requires init_app with the app instance.