flask_sqlalchemy multiple databases bind issue

31 Views Asked by At

I am trying to use multiple DB endpoints for my Flask App. This is how I am starting my Flask App and this is how I am initializing the app

def create_app():
    """
        Build and return a new flask app
    """
    app = FlaskLambda(__name__)
    
    app.config.from_object(Configuration)
    
    """ bind both read and write  """
    app.config['SQLALCHEMY_BINDS'] = {
        'read': app.config['SQLALCHEMY_READ'],
        'write': app.config['SQLALCHEMY_WRITE']
    }
    db = SQLAlchemy(model_class=CustomModel, query_class=CustomQuery, session_options={"autoflush": False})
    db.init_app(app)

My Configuration class is like below

from flask_env import MetaFlaskEnv


class Configuration(metaclass=MetaFlaskEnv):
    SQLALCHEMY_DATABASE_URI = ''
    SQLALCHEMY_READ = ''
    SQLALCHEMY_WRITE = ''

My route is like below

def get_data(store_id, **kwargs):
    bind_ = db.get_engine(current_app, "read")
    data = db.session.execute("SELECT * FROM table1 WHERE id = :id", {"id": id} , bind = bind_).fetchone() or {} # this hits the proper engine

    session = scoped_session(sessionmaker(bind=bind_))
    return json_response(MyController(session).get(id, **kwargs)) # this still hits the default `SQLALCHEMY_DATABASE_URI` 

How to fix this .

0

There are 0 best solutions below