LifetimeControllerMiddleware analog from aiogram2 to aiogram3

111 Views Asked by At

In aiogram2 I have the code:

class DatabaseMiddleware(LifetimeControllerMiddleware):
    def __init__(self, async_session_maker):
        super().__init__()
        self.async_session_maker = async_session_maker

    async def pre_process(self, obj, data, *args):
        session: AsyncSession = self.async_session_maker()
        data["session"] = session
        data["repo"] = Repo(session=session)

    async def post_process(self, obj, data, *args):
        del data["repo"]
        session: AsyncSession = data.get("session")
        await session.close()

But there is no LifetimeControllerMiddleware in aiogram3, how do I replace LifetimeControllerMiddleware in aiogram3?

class DatabaseMiddleware(BaseMiddleware):

    def __init__(self, async_session_maker):
        super().__init__()
        self.async_session_maker = async_session_maker

    async def __call__(
                self,
                handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
                event: TelegramObject,
                data: Dict[str, Any]
            ) -> Any:

            session: AsyncSession = self.async_session_maker()
            data["session"] = session
            data["repo"] = Repo(session=session)
            return await handler(event, data)

Error:

SAWarning: The garbage collector is trying to clean up non-checked-in connection <AdaptedConnection <asyncpg.connection.Connection object at 0x000001ACE7450C80>>, which will be terminated. Please ensure that SQLAlchemy pooled connections are returned to the pool explicitly, either by calling close() or by using appropriate context managers to manage their lifecycle. schema = self._schema_type_to_method[schema['type']](schema.copy(), f) ERROR:sqlalchemy.pool.impl.QueuePool:The garbage collector is trying to clean up non-checked-in connection <AdaptedConnection <asyncpg.connection.Connection object at 0x000001ACE613F060>>, which will be terminated. Please ensure that SQLAlchemy pooled connections are returned to the pool explicitly, either by calling close() or by using appropriate context managers to manage their lifecycle.

0

There are 0 best solutions below