我正在对Alasbic + sqlalchemy项目使用Alembic迁移,并且一切正常,直到尝试在Alembic中查询模型。
from models import StoredFile
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('stored_file', sa.Column('mimetype', sa.Unicode(length=32))
for sf in StoredFile.query.all():
sf.mimetype = guess_type(sf.title)
上面的代码被卡住了[[之后添加列,并且永远不会出来。我猜想StoredFile.query
正在尝试使用与alembic正在使用的数据库连接不同的数据库连接。 (但是为什么?我在env.py
中缺少什么?)
op.get_bind().execute(...)
来解决,但问题是如何直接在Alembic中使用模型?models
中的类。如果需要使用模型类,则应在每个迁移文件中重新定义它们,以使迁移自包含。原因是可以在一个命令中部署多个迁移,并且有可能在编写迁移的时间到实际在生产中执行迁移之间,已根据“后期”迁移更改了模型类。例如,请参见Operations.execute文档中的以下示例:
from sqlalchemy.sql import table, column
from sqlalchemy import String
from alembic import op
account = table('account',
column('name', String)
)
op.execute(
account.update(). \
where(account.c.name==op.inline_literal('account 1')). \
values({'name':op.inline_literal('account 2')})
)
提示:您不需要包括完整的模型类,仅需要迁移所必需的部分。
StoredFile.query
时,您使用的会话与Alembic使用的会话不同。它尝试查询数据库,但表已锁定,因为您正在对其进行更改。因此,升级就在那里,并且永远等待,因为您有两个会话在等待彼此。基于@SowingSadness响应,这对我有用:from models import StoredFile
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('stored_file', sa.Column('mimetype', sa.Unicode(length=32))
connection = op.get_bind()
SessionMaker = sessionmaker(bind=connection.engine)
session = SessionMaker(bind=connection)
for sf in session.query(StoredFile):
sf.mimetype = guess_type(sf.title)
session.flush()
op.other_operations()