felicity-lims/backend/felicity_lims/felicity/database/session.py

35 lines
1,000 B
Python
Raw Normal View History

from typing import AsyncGenerator
from asyncio import current_task
2021-09-19 09:43:55 +08:00
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_scoped_session
2021-01-06 19:52:14 +08:00
from felicity.core.config import settings
async_engine = create_async_engine(settings.SQLALCHEMY_ASYNC_DATABASE_URI, pool_pre_ping=True, echo=True, future=True)
AsyncSessionLocal = sessionmaker(
bind=async_engine,
expire_on_commit=False,
2021-09-19 09:43:55 +08:00
autoflush=False,
class_=AsyncSession,
2021-09-19 09:43:55 +08:00
)
AsyncSessionScoped = async_scoped_session(AsyncSessionLocal, scopefunc=current_task)
# Async Dependency
async def get_session() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session
# or Async Dependency 2
async def get_db() -> AsyncGenerator:
session = AsyncSessionLocal()
try:
yield session
await session.commit()
except AsyncSessionLocal as ex:
await session.rollback()
raise ex
finally:
await session.close()