Dev*_*evi 6 sqlalchemy flask-sqlalchemy alembic
我正在使用alembic迁移进行烧瓶+ sqlalchemy项目,事情按预期工作,直到我尝试查询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)
Run Code Online (Sandbox Code Playgroud)
上面的代码在添加列后卡住了,永远不会出现.我想这StoredFile.query是尝试使用与alembic使用的数据库连接不同的数据库连接.(但为什么?我错过了什么env.py?)
我可以通过使用来解决它,op.get_bind().execute(...)但问题是我如何直接在alembic中使用模型?
你不应该models在你的 alembic 迁移中使用类。如果您需要使用模型类,您应该在每个迁移文件中重新定义它们以使迁移独立。原因是可以在一个命令中部署多个迁移,并且可能在编写迁移到实际在生产中执行之间,模型类已根据“稍后”迁移进行了更改。
例如,请参阅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')})
)
Run Code Online (Sandbox Code Playgroud)
提示:您不需要包含完整的模型类,只需包含迁移所需的部分。
小智 4
我有同样的问题。当您使用时,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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1269 次 |
| 最近记录: |