I trying to make async database request using sqlalachemy like described in example : https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#synopsis-orm under title : Preventing Implicit IO when Using AsyncSession. As i understood from code exist two ways to create session :
- using async_session = AsyncSession(engine, expire_on_commit=False)
- or using sessionmaker with class_=AsyncSession parameter
my code looks like following :
async def setup_connection(self):
self.logger.info("Pause to be sure that i am async")
await asyncio.sleep(1)
self.logger.info("Async Pause finished")
self.logger.info("Database engine uri: %s", self.database_engine_uri)
self.database_engine = create_async_engine(self.database_engine_uri, pool_size=self.pool_size, echo=True)
async_session = AsyncSession(self.database_engine, expire_on_commit=False)
self.logger.info("Before hang")
async with async_session() as session:
self.logger.info("Inside with")
....
After i execute my code i get following :
2021-06-17 16:07:52,942 File:database.py Function:setup_connection Line:46 Pause to be sure that i am async
2021-06-17 16:07:53,943 File:database.py Function:setup_connection Line:48 Async Pause finished
2021-06-17 16:07:53,943 File:database.py Function:setup_connection Line:49 Database engine uri: mysql+aiomysql://user:password@10.111.117.9/db
2021-06-17 16:07:53,954 File:database.py Function:setup_connection Line:53 Before hang
It is feels like code just hang in moment of execution "async with async_session() as session:" because next log message never appear. Can you please help me with proper and simplest way to use asyncio with sqlalachemy.