You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:42:46