felicity-lims/felicity/database/session.py

48 lines
1.3 KiB
Python
Raw Normal View History

2023-08-14 02:08:08 +08:00
from asyncio import current_task
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_scoped_session,
create_async_engine,
)
from sqlalchemy.orm import sessionmaker
from felicity.core import get_settings
settings = get_settings()
2023-09-14 16:35:24 +08:00
2023-08-14 02:08:08 +08:00
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI)
async_engine = create_async_engine(
2023-09-14 16:35:24 +08:00
settings.SQLALCHEMY_TEST_DATABASE_URI
2023-08-14 02:08:08 +08:00
if settings.TESTING
2023-09-14 16:35:24 +08:00
else settings.SQLALCHEMY_DATABASE_URI,
2023-08-14 02:08:08 +08:00
pool_pre_ping=True,
echo=False,
future=True,
)
# async_session_factory can be used directly using: async with async_session_factory() as session: ...
async_session_factory = sessionmaker(
bind=async_engine, expire_on_commit=False, autoflush=False, class_=AsyncSession
)
AsyncSessionScoped = async_scoped_session(async_session_factory, scopefunc=current_task)
# # Async Dependency
# async def get_session() -> AsyncGenerator:
# async with async_session_factory() as session:
# yield session
# # or
# async def get_db() -> AsyncGenerator:
# session = async_session_factory()
# try:
# yield session
# await session.commit()
# except async_session_factory as ex:
# await session.rollback()
# raise ex
# finally:
# await session.close()