使用aiogram+asyncpg+SQLAlchemy时遇__enter__未被await错误求助
问题:aiogram+asyncpg+PostgreSQL异步数据库操作异常
- 此前为解决
__enter__未定义错误编写了CustomSession类,现在出现__enter__无法被await的问题 - 若将
__enter__改为非协程方法,会抛出协程错误,要求__enter__内的操作都使用await,但这又需要先await__enter__本身 - 目前数据库无法写入数据,不确定问题是否出在其他环节
相关代码
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()
使用版本
aiogram==2.25.1 asyncpg==0.28.0 SQLAlchemy==2.0.19 Python 3.10.12 asyncio-3.4.3
内容的提问来源于stack exchange,提问作者Ani
相关产品推荐
相关产品推荐

