mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2026-01-17 11:40:39 +03:00
database refactor and remove redundant code
This commit is contained in:
@@ -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()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user