mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
wrap db session with context manager
This commit is contained in:
parent
518102860b
commit
96ee8e43e0
@ -1,5 +1,6 @@
|
|||||||
from typing import AsyncGenerator
|
from typing import AsyncGenerator
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
from sqlalchemy.exc import SQLAlchemyError
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
@ -22,13 +23,15 @@ async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession
|
|||||||
|
|
||||||
# Dependency
|
# Dependency
|
||||||
async def get_db() -> AsyncGenerator:
|
async def get_db() -> AsyncGenerator:
|
||||||
session = async_session()
|
async with async_session() as session:
|
||||||
try:
|
try:
|
||||||
yield session
|
yield session
|
||||||
await session.commit()
|
await session.commit()
|
||||||
except SQLAlchemyError as ex:
|
except SQLAlchemyError as sql_ex:
|
||||||
await session.rollback()
|
await session.rollback()
|
||||||
raise ex
|
raise sql_ex
|
||||||
finally:
|
except HTTPException as http_ex:
|
||||||
await session.close()
|
session.rollback()
|
||||||
|
raise http_ex
|
||||||
|
finally:
|
||||||
|
await session.close()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user