#๐Ÿ”’ Managing Async SQLalchemy sessions.

4 messages ยท Page 1 of 1 (latest)

idle grail
#

I like this style of writing routes in FastAPI. But it seems to be flawed.

@router.get('/items', response_model=list[AvatarPropertyItemOut])
async def get_avatar_items(
    service: Annotated[AvatarService, Depends(get_avatar_service)],
) -> list[AvatarPropertyItemOut]:
    """Get the list of avatar items."""
    return await service.get_avatar_items()
async def get_avatar_service() -> AvatarService:
    """Get the avatar service."""
    async with async_session_maker() as session:
        avatar_repo = AvatarRepository(session)
        return AvatarService(
            avatar_repo=avatar_repo,
        )
@asynccontextmanager
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
    """Get the database session."""
    async with async_session_maker() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()

But it seems like the object stays alive after the route is done.
So the connection to database doesn't get closed.

I don't really want to do the Depends in every route for getting session.
And writing session injection in every route.
And possibly passing session to every method of service classes.

Is there a way to make this approach possible? :\

plush caveBOT
#

@idle grail

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

plush caveBOT
#

@idle grail

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.