r/FastAPI • u/Cherriedy • Sep 11 '25
Question Having trouble with asyc_sessiomaker in FastAPI
I'm buiding endpoints with FastAPI, PostgreSQL as database, and the driver is asyncpg associated with SQLAlchemy for asynchronous. As mentioned in the title, I'm having trouble with async_sessionmaker, it keeps showing: 'async_sessionmaker' object does not support the asynchronous context manager protocol.
Here the part of code in repository:
class GenreRepositoryImpl(GenreRepository):
def __init__(self, sessionmaker: async_sessionmaker[AsyncSession]):
self._sessionmaker = sessionmaker
async def create(self, genre: Genre) -> Genre:
genre_entity = GenreEntityMappers.from_domain(genre)
async with self._sessionmaker() as session:
session.add(genre_entity)
await session.commit()
await session.refresh(genre_entity)
return GenreEntityMappers.to_domain(genre_entity)Somehow it works when I use it as transaction with begin(), I don't understand what's wrong.
5
Upvotes
2
u/koldakov Sep 11 '25
Hi, what’s the sessionmaker here?
1
u/Fun-Lecture-1221 Sep 12 '25
I've already implement similar pattern for my project which looks like below.
with this, i could do
Depends(get_db)which will return async session and do something with it.1
u/Jotheavg123 Sep 11 '25
How are you initialising your class? It looks like self._sessionmaker() is returning async_sessionmaker object instead of AsyncSession. What are you passin in sessionmaker during init?
1
u/Ferdinand_the_II Sep 16 '25
Guys! Is there common behaviour when PostgreSQL keep sessions active even when async_sessionmaker generator is finished and close session? I have my sessions active on my database dashboard…