0

I have troubles with aiogram+asyncpg+postgresql. I have already explicitly written a class for __enter__ to be defined as I received an error of it being undefined, though now I have a problem of it being unable to be awaited. When I make it non-coroutine, it throws a coroutine error and asks for everything within the __enter__ method to be awaited, and it cannot be done without awaiting __enter__ itself (can it?). I have no idea how to fix it. Maybe the problem lies somewhere else as without it nothing adds to the database.

The code is the following:

main.py:

import asyncio
from core import dp
from aiogram import executor

import nest_asyncio
nest_asyncio.apply( )


async def run():
    executor.start_polling(dp)


loop = asyncio.get_event_loop()


if __name__ == '__main__':
    loop.run_until_complete(run())

database_commands.py:

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import IntegrityError


def add_item_to_db(item, new_async_session: AsyncSession):
    with new_async_session() as new_session:
        with new_session.begin():
            new_session.add_all([item])
            try:
                new_session.commit()
                new_session.refresh(item)
                new_session.close()
                return item
            except IntegrityError:
                new_session.rollback()

database_append_user.py:

...
await add_item_to_db(item=new_user, new_async_session=CustomSession)
...

database_engine.py:

...
async_session_maker = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


async def get_db() -> AsyncGenerator:
    async with async_session_maker() as db:
        try:
            yield db
        finally:
            await db.close()


class CustomSession:
    def __init__(self):
        self.session = async_session_maker()

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.session.close()

    async def __enter__(self):
        return await self.session

    async def __aenter__(self):
        return await self.session

    async def __exit__(self, exc_type, exc_val, exc_tb):
        await self.session.close()

I am using:

aiogram==2.25.1
asyncpg==0.28.0
SQLAlchemy==2.0.19
Python 3.10.12
asyncio-3.4.3
Anna
  • 101
  • 8
  • Why is `add_item_to_db` synchronous? It looks like you're trying a bunch of ad-hoc fixes in an attempt to call async code from synchronous code, when the synchronous code shouldn't be synchronous in the first place. – user2357112 Aug 15 '23 at 11:43
  • @user2357112 making it asynchronous doesn't help – Anna Aug 15 '23 at 12:15
  • 1
    Yeah, because you need to fix a bunch of other stuff on top of that, but those fixes need to be completely different from the stuff you were trying. (A lot of the stuff you need to fix might consist of rolling back the stuff you were already trying.) For example, it looks like you either forgot the `async` on your `async with`, or took it off because Python told you you couldn't do that in a sync function. – user2357112 Aug 15 '23 at 12:21

0 Answers0