felicity-lims/felicity/database/session.py

44 lines
1.1 KiB
Python
Raw Normal View History

from asyncio import current_task
from typing import AsyncGenerator
2021-01-06 19:52:14 +08:00
2023-03-19 23:21:32 +08:00
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_scoped_session,
create_async_engine,
)
from sqlalchemy.orm import sessionmaker
2023-03-19 23:21:32 +08:00
from felicity.core.config import settings
async_engine = create_async_engine(
2023-04-07 23:52:19 +08:00
settings.SQLALCHEMY_TEST_ASYNC_DATABASE_URI
if settings.TESTING
else settings.SQLALCHEMY_ASYNC_DATABASE_URI,
2023-03-19 23:21:32 +08:00
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
)
2023-04-10 09:29:10 +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()