'multiple database backends per session along with db.execute when using sqlaclhemy

I have this database connection in a fast API app. I am using multiple binds to the same session, I followed the documentation here: Query the db:

method1: working

db.query(Model).all()

method2: not working and throwing the following error:

db.execute("SELECT * from ...");

Exception has occurred: UnboundExecutionError
Could not locate a bind configured on SQL expression or this Session.

This is the database connection code... Can you help me get method2 working?

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import MetaData
from app.settings import (
    db1_DATABASE_URL,
    db2_DATABASE_URL
)


engine = create_engine(
    db1_DATABASE_URL,
    echo=False,
    pool_recycle=1800,
    pool_timeout=20,
    pool_pre_ping=True,
    pool_size=50,
    max_overflow=100,
)

engine2 = create_engine(db2_DATABASE_URL)


Base = declarative_base()

mroi_Base = automap_base()
mroi_Base.prepare(engine2, reflect=True)

SessionLocal = sessionmaker(autocommit=False, autoflush=False)
SessionLocal.configure(binds={Base: engine, mroi_Base: engine2})


def get_db():
    db = None
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


def get_db2():
    db2 = None
    try:
        db2 = SessionLocal()
        yield db2
    finally:
        db2.close()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source