ceharep
ceharep

Reputation: 439

Flask-SQLAlchemy - how to a autoload a table from a Bind (second database)

Is it possible to use autoload for a table in Flask-SQLAlchemy when using a secondary database?

I've tried to set up bind_key in config.py so that I can access two separate databases, but I can't get it to autoload the table from the secondary database db2

from flask import Flask, jsonify, abort, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
migrate = Migrate(app, db)

class TAB1(db.Model):
    __tablename__ = 'TABLE1'
    __bind_key__ = 'db1'
    __table_args__ = {
        'autoload': True,
        'autoload_with': db.engine
    }
    
class TAB2(db.Model):
    __bind_key__ = 'db2'
    __tablename__ = 'TABLE2'

    __table_args__ = {
        'autoload': True,
        'autoload_with': db.engine
    }

config.py

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://root:example@database1-db:9001/database1"
SQLALCHEMY_BINDS = {
    'db2': "postgres://postgres:example@database2-db:9002/database2",
    'db1': SQLALCHEMY_DATABASE_URI
}

I get an error:

sqlalchemy.exc.NoSuchTableError: `TABLE2`

I suspect that I need to change the autoload_with to refer to the bind_key in some way, but can't work out how?

Upvotes: 1

Views: 878

Answers (2)

Ssali Jonathan
Ssali Jonathan

Reputation: 97

'autoload_with' :db.get_engine(bind_key='your_bind_key')

Upvotes: -1

ceharep
ceharep

Reputation: 439

Worked it out, it's:

'autoload_with': db.get_engine(bind="db2")

Upvotes: 1

Related Questions