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

35 lines
1 KiB
Python
Raw Normal View History

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