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