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
80%Fix Rate
87%Confidence
0Evidence
2024-10-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
Create db once in extensions.py: from flask_sqlalchemy import SQLAlchemy; db = SQLAlchemy() # import everywhere else
-
92% success
In factory: from .extensions import db; db.init_app(app) # only once
Dead Ends
Common approaches that don't work:
-
90% fail
Raises again; second instance is unusable.
-
70% fail
Old versions silently misbehave; data bugs appear later.