属性错误:异步 SQLalchemy 会话中的 __aenter__

问题描述 投票:0回答:1

我使用这样的会话遇到

AttributeError: __aenter__
错误:

    async def get_session():
        SessionLocal = sessionmaker(
            autocommit=False,
            autoflush=False,
            bind=engine,
            expire_on_commit=False,
            class_=AsyncSession,
        )

        async with SessionLocal() as session:
            yield session

    async def insert(data_array):
        async with get_session() as session:
            session.add_all(data_array)
            await session.commit()

    await insert(reports)

此处发生错误

async with get_session() as _session:
我猜在调试器中
get_session()
是生成器,但里面没有
__aenter__
属性

我使用的是asyncio,连接的数据库是postgres 我的sqlalchemy版本是2.0.28

我尝试了一些改变

sessionmaker
但没有给出任何结果

python postgresql sqlalchemy python-asyncio
1个回答
0
投票

您应该使用

async_sessionmaker
而不是
sessionmaker

from sqlalchemy.ext.asyncio import async_sessionmaker

并使用

create_async_engine

创建引擎
from sqlalchemy.ext.asyncio import create_async_engine
© www.soinside.com 2019 - 2024. All rights reserved.