Package: fastapi-async-sqlalchemy
SQLAlchemy FastAPI middlewareDescriptionProvides SQLAlchemy middleware for FastAPI using AsyncSession and async engine.Installpipinstallfastapi-async-sqlalchemyImportant !!!If you usesqlmodelinstallsqlalchemy<=1.4.41ExamplesNote that the session object provided bydb.sessionis based on the Python3.7+ContextVar. This means that
each session is linked to the individual request context in which it was created.fromfastapiimportFastAPIfromfastapi_async_sqlalchemyimportSQLAlchemyMiddlewarefromfastapi_async_sqlalchemyimportdb# provide access to a database sessionfromsqlalchemyimportcolumnfromsqlalchemyimporttableapp=FastAPI()app.add_middleware(SQLAlchemyMiddleware,db_url="postgresql+asyncpg://user:user@192.168.88.200:5432/primary_db",engine_args={# engine arguments example"echo":True,# print all SQL statements"pool_pre_ping":True,# feature will normally emit SQL equivalent to “SELECT 1” each time a connection is checked out from the pool"pool_size":5,# number of connections to keep open at a time"max_overflow":10,# number of connections to allow to be opened above pool_size},)# once the middleware is applied, any route can then access the database session# from the global ``db``foo=table("ms_files",column("id"))# Usage inside of a route@app.get("/")asyncdefget_files():result=awaitdb.session.execute(foo.select())returnresult.fetchall()asyncdefget_db_fetch():# It uses the same ``db`` object and use it as a context manager:asyncwithdb():result=awaitdb.session.execute(foo.select())returnresult.fetchall()# Usage inside of a route using a db context@app.get("/db_context")asyncdefdb_context():returnawaitget_db_fetch()# Usage outside of a route using a db context@app.on_event("startup")asyncdefon_startup():# We are outside of a request context, therefore we cannot rely on ``SQLAlchemyMiddleware``# to create a database session for us.result=awaitget_db_fetch()if__name__=="__main__":importuvicornuvicorn.run(app,host="0.0.0.0",port=8002)Usage of multiple databasesdatabases.pyfromfastapiimportFastAPIfromfastapi_async_sqlalchemyimportcreate_middleware_and_session_proxyFirstSQLAlchemyMiddleware,first_db=create_middleware_and_session_proxy()SecondSQLAlchemyMiddleware,second_db=create_middleware_and_session_proxy()main.pyfromfastapiimportFastAPIfromdatabasesimportFirstSQLAlchemyMiddleware,SecondSQLAlchemyMiddlewarefromroutesimportrouterapp=FastAPI()app.include_router(router)app.add_middleware(FirstSQLAlchemyMiddleware,db_url="postgresql+asyncpg://user:user@192.168.88.200:5432/primary_db",engine_args={"pool_size":5,"max_overflow":10,},)app.add_middleware(SecondSQLAlchemyMiddleware,db_url="mysql+aiomysql://user:user@192.168.88.200:5432/primary_db",engine_args={"pool_size":5,"max_overflow":10,},)routes.pyfromfastapiimportAPIRouterfromsqlalchemyimportcolumnfromsqlalchemyimporttablefromdatabasesimportfirst_db,second_dbrouter=APIRouter()foo=table("ms_files",column("id"))@router.get("/first-db-files")asyncdefget_files_from_first_db():result=awaitfirst_db.session.execute(foo.select())returnresult.fetchall()@router.get("/second-db-files")asyncdefget_files_from_second_db():result=awaitsecond_db.session.execute(foo.select())returnresult.fetchall()