database refactor and remove redundant code

This commit is contained in:
Jakub Miazek
2022-09-27 12:54:37 +02:00
parent 9b1938c450
commit 307feeeade
20 changed files with 9 additions and 729 deletions

View File

@@ -1,8 +1,11 @@
from asyncio import current_task
from typing import AsyncGenerator
from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_scoped_session
from sqlalchemy.orm import sessionmaker
from app import config
@@ -14,16 +17,18 @@ engine = create_async_engine(
url,
future=True,
echo=True,
json_serializer=jsonable_encoder,
)
# expire_on_commit=False will prevent attributes from being expired
# after commit.
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
async_session_factory = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
AsyncScopedSession = async_scoped_session(async_session_factory, scopefunc=current_task)
# Dependency
async def get_db() -> AsyncGenerator:
async with async_session() as session:
async with async_session_factory() as session:
try:
yield session
await session.commit()
@@ -35,3 +40,4 @@ async def get_db() -> AsyncGenerator:
raise http_ex
finally:
await session.close()