flask-sqlalchemy icon indicating copy to clipboard operation
flask-sqlalchemy copied to clipboard

Connecting multiple pre-exising databases via binds

Open daniel-saunders opened this issue 9 years ago • 3 comments

Hi. I'm new to flask-sqlalchemy. I have multiple pre-existing mysql databases (for this example, two is enough). I have created a minimal example of what I'm trying to do below. I'm able to successful connect to one database using SQLALCHEMY_DATABASE_URI. For the second database, I'm trying to use SQLALCHEMY_BINDS to connect to the other database, but i am unable to access it. I've been unable to find an example that uses binding with pre-existing databases. Any help would be appreciated.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# db1 - works ok.
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/SiPMCalibration'

# db2 - not working.
app.config['SQLALCHEMY_BINDS'] = {
    'db2': 'mysql://user:password@localhost/Run8Chan'
}

db = SQLAlchemy(app)
db.Model.metadata.reflect(db.engine)

# Setup the model for the pre-existing table.
class sipm_calibration(db.Model):
	__table__ = db.Model.metadata.tables['Calibration']

# Some code to retrive the most recent 100 entries and print their headers (i.e keys)
query = db.session.query(sipm_calibration).order_by(sipm_calibration.ID.desc()).limit(100)
print db.session.execute(query).keys() # Works fine.

#---------------------
# All ok so far - try again for the second database via binding.
class run_entry(db.Model):
    __bind_key__ = 'db2'
    __table__ = db.Model.metadata.tables['Runs']

query = db.session.query(run_entry).order_by(run_entry.ID.desc()).limit(100)
print db.session.execute(query).keys()

daniel-saunders avatar Mar 20 '17 14:03 daniel-saunders

The actual problem is when looking for the 'Runs' database table at line:

__table__ = db.Model.metadata.tables['Runs']

daniel-saunders avatar Mar 20 '17 14:03 daniel-saunders

Please use Stack Overflow for questions about your own code. This tracker is for issues with Flask-SQLAlchemy itself.

davidism avatar Mar 21 '17 14:03 davidism

@daniel-saunders Have you resolved the problem? I voted that that was caused by Flask-SQLarchemy buggy implementation

yiakwy avatar Sep 11 '18 03:09 yiakwy