Merge pull request #21 from grillazz/json-field-example

wrap db session with context manager
This commit is contained in:
Jakub Miazek 2022-02-18 09:27:13 +01:00 committed by GitHub
commit 774c5f506a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,6 @@
from typing import AsyncGenerator
from fastapi import HTTPException
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
@ -22,13 +23,15 @@ async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession
# Dependency
async def get_db() -> AsyncGenerator:
session = async_session()
async with async_session() as session:
try:
yield session
await session.commit()
except SQLAlchemyError as ex:
except SQLAlchemyError as sql_ex:
await session.rollback()
raise ex
raise sql_ex
except HTTPException as http_ex:
session.rollback()
raise http_ex
finally:
await session.close()