SQLAlchemy AttributeError:“AsyncEngine”对象没有属性“_run_ddl_visitor”

Nyx*_*nyx 8 python postgresql sqlalchemy python-3.x python-asyncio

我正在尝试在应用程序中使用 SQLAlchemy 的异步版本asyncio。但是,当尝试使用创建表时Metadata().create_all(),会出现以下错误

AttributeError:“AsyncEngine”对象没有属性“_run_ddl_visitor”

我们如何解决这个问题?谢谢!

import asyncio
from sqlalchemy import Column, String, 
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.sql.schema import MetaData
from sqlalchemy.ext.asyncio import create_async_engine


connection_url = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{dbname}"
engine = create_async_engine(connection_url)
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db_session = scoped_session(Session)

Base = declarative_base()
Base.query = db_session.query_property()

class Foo(Base):
    __tablename__ = "foo"    
    id = Column(String, primary_key=True)
    name = Column(String)

class Store:
    def __init__(self):
        super().__init__()
        self.connection = None

    async def connect(self):
        self.connection = await engine.begin()
        metadata = MetaData(bind=engine)
        await self.connection.run_sync(metadata.create_all())
    

async def main():
    store = Store()
    await store.connect()

if __name__ == '__main__':
    asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

尝试#2

import asyncio
from sqlalchemy import Column, String, 
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.sql.schema import MetaData
from sqlalchemy.ext.asyncio import create_async_engine


connection_url = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{dbname}"
engine = create_async_engine(connection_url)
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)

Base = declarative_base()

class Foo(Base):
    __tablename__ = "foo"    
    id = Column(String, primary_key=True)
    name = Column(String)
    __mapper_args__ = {"eager_defaults": True}

class Store:
    def __init__(self):
        super().__init__()

    async def connect(self):
        async with async_session() as db_session:
            async with db_session.begin():
                await db_session.run_sync(Base.metadata.create_all)

async def main():
    store = Store()
    await store.connect()

if __name__ == '__main__':
    asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

错误:

AttributeError:“会话”对象没有属性“_run_ddl_visitor”

Opt*_*RUS 12

代替:

Base.metadata.create_all(engine)
Run Code Online (Sandbox Code Playgroud)

有了这个:

async def init_models():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

asyncio.run(init_models())
Run Code Online (Sandbox Code Playgroud)

详细信息:

@app.on_event("startup")
async def init_tables():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

@app.post("/users")
async def create_user(user: User):
    async with async_session() as session:
        session.add(UserModel(**user.dict()))
        await session.flush()
        await session.commit()
        return UserResponse.from_orm(user)
Run Code Online (Sandbox Code Playgroud)

  • 正如目前所写的,您的答案尚不清楚。请[编辑]添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以[在帮助中心](/help/how-to-answer)找到有关如何写出好的答案的更多信息。 (7认同)