I have a flask app currently using SQL alchemy (Version: 3.1.1) to connect to one database, but I am trying to change my config so that I can connect to more databases as the app grows. Below is the config information being used in the implementation file of a deamon for the flask app.
username = "user"
password = "pass"
hostname = "host"
port = "port"
db_one = "db_one"
db_two = "db_two"
self.flask_app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql://{username}:{password}@{hostname}:{port}/{db_one}"
self.flask_app.config['SQLALCHEMY_BINDS'] = {
'db_two': f"mysql://{username}:{password}@{hostname}:{port}/{db_two}"}
This then gets initialized at the end of the file
daemon_app = CustomApi()
db = SQLAlchemy(daemon_app.flask_app)
flask_app = daemon_app.flask_app
I have a separate file called models.py that currently reflects the default db and gives me access to tables so that I can modify the data, which works fine.
from ....daemon.implementation import flask_app, db
with flask_app.app_context():
db.reflect()
class TestModel(db.Model):
__table__ = db.Model.metadata.tables["test_table"]
My current issue/s is that I am struggling to set up models for the second schema. So far, I had this working in terms of reflecting:
from ....daemon.implementation import flask_app, db
with flask_app.app_context():
metadata = db.MetaData()
metadata.reflect(bind=db.get_engine(bind='db_two'))
class TestModelTwo(db.Model):
__bind_key__ = 'db_two'
__table__ = metadata.tables["test_table_two"]
The code above does not throw any errors. However, when I try to run a query in a route in a different file, I am not able to declare which bind to use. I have a snippet of the code below that throws the error below:
response = (
db.session.query(TestModelTwo).first()
)
The error says that there is not table named test_table_two in schema db_one which shows me that the query is still running on the default schema.
I’ve also tried including the bind in the query, but it still wants to check db_one instead
response = db.session.query(TestModelTwo).execution_options(bind=db.get_engine(bind='db_two')).first()
Help on any step is appreciated. Thanks!