我正在尝试在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’
1条答案
按热度按时间wwtsj6pe1#
替换:
有了这一点:
具体来说: