SQLAlChemy AttributeError:“”AsyncEngine“”对象没有属性“”_RUN_DDL_VIRECTOR“”

t3psigkw  于 2022-10-15  发布在  PostgreSQL
关注(0)|答案(1)|浏览(694)

我正在尝试在asyncio应用程序中使用SQLAlChemy的异步版本。但是,尝试使用Metadata().create_all()创建表时,会出现以下错误
AttributeError:“”AsyncEngine“”对象没有属性“”_RUN_DDL_VIRECTOR“”
我们如何解决这个问题?谢谢!

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())

尝试#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())

错误:
AttributeError:‘Session’对象没有属性‘_RUN_DDL_VIRECTOR’

wwtsj6pe

wwtsj6pe1#

替换:

Base.metadata.create_all(engine)

有了这一点:

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())

具体来说:

@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)

相关问题