python config_error ai_generated true

RuntimeError: A 'SQLAlchemy' instance has already been registered on this Flask app. Import and use that instance instead.

ID: python/flask-sqlalchemy-multiple-instances

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Two db = SQLAlchemy() objects created in different modules and both init_app(app) called.

generic

中文

在不同模块中创建了两个 db = SQLAlchemy() 对象,并且都调用了 init_app(app)。

Workarounds

  1. 95% success
    Create db once in extensions.py: from flask_sqlalchemy import SQLAlchemy; db = SQLAlchemy()  # import everywhere else
  2. 92% success
    In factory: from .extensions import db; db.init_app(app)  # only once

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Raises again; second instance is unusable.

  2. 70% fail

    Old versions silently misbehave; data bugs appear later.