import os import dotenv from config.constant import EnvPostgresConstants, EnvFilepath dotenv.load_dotenv(EnvFilepath.ENVPATH) from contextlib import asynccontextmanager from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession from sqlalchemy.orm import declarative_base DATABASE_URL = EnvPostgresConstants.CONSTRING.\ replace("postgresql+psycopg2", "postgresql+asyncpg") engine = create_async_engine( DATABASE_URL, echo=False, future=True ) AsyncSessionLocal = async_sessionmaker( engine, expire_on_commit=False, class_=AsyncSession ) Base = declarative_base() # async def get_db(): # async with AsyncSessionLocal() as session: # try: # return session # finally: # await session.close() async def get_db(): async with AsyncSessionLocal() as session: try: yield session finally: await session.close() # async def get_db_session(): # session = AsyncSessionLocal() # try: # return session # except: # await session.close() # raise @asynccontextmanager async def db_session(): async with AsyncSessionLocal() as session: try: yield session finally: await session.close()