python runtime_error ai_generated true

RuntimeError: 当前 Flask 应用未注册到此 'SQLAlchemy' 实例。是否忘记调用 'init_app'?

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-01-16首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 85% 失败

    No app context; raises the same error.

  2. 70% 失败

    Still requires init_app with the app instance.