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 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
except HTTPException as http_ex:
session.rollback()
raise http_ex
finally: finally:
await session.close() await session.close()