FastAPI to handle multiple DB connections via SqlAlchemy

2.2k Views Asked by At

Can we declare multiple databases sessions in fast api like this?


Base = declarative_base()

@contextmanager
def get_db(db_type: str):
    if db_type == "retention":
        db = RetentionSessionLocal()
    else:
        db = SessionLocal()
    try:
        yield db
        db.commit()
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()

Where RetentionSessionLocal is pointing to different database and SessionLocal is pointing to main db.

And also is declarative_base() same for any database or it have to change?

And if the above is something can be done then how can we declare models to respective databases to do CRUD operations?


Update: Not using this code anymore but may be useful as it is a working code earlier handling two databases:

engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

RETENTION_DATABASE_URL = "postgresql+psycopg2://{0}:{1}@{2}:{3}/{4}".format(
    os.environ["DB_USERNAME"],
    os.environ["DB_PASSWORD"],
    os.environ["DB_HOST"], "5432",
    os.environ["RETENTION_DB"]
)
retention_engine = create_engine(RETENTION_DATABASE_URL, pool_pre_ping=True)
RetentionSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=retention_engine)
MainBase = declarative_base()
RetentionBase = declarative_base()
0

There are 0 best solutions below