我如何在Flask-Migrate / Flask-SQLAlchemy中正确编辑Alembic迁移脚本以添加或编辑列?

问题描述 投票:0回答:1

我正在使用一个小应用程序来从在线文章中抓取数据。

[当前,我试图弄清楚如何从Flask-migrate编辑迁移脚本,因此不必删除所有迁移数据,而SQlite数据库则在每次编辑架构时都重新擦除数据!] >

当然,当我编辑模型,删除所有内容,重新初始化并再次刮取数据时,数据库适应得很好。但是,当我尝试手动编辑它时,它会运行升级,但是我发现数据没有变化。

下面的例子...

迁移脚本:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('article', sa.Column('example', sa.DateTime(), nullable=True))
    # ### end Alembic commands ###

我也曾尝试添加它以用数据填充它,但是由于列不存在(当然,如果我遗漏了一些内容,请纠正我),它当然没有成功:

from datetime import datetime

...
def upgrade():
...
     op.execute("UPDATE article SET example = datetime.utcnow()")  # (new scraped data would get a new
                                                                   # timestamp but this would be fine
                                                                   # for old data for my purposes)

我对SQL及其框架还很陌生,但是在有索引和无索引的情况下,我都做了这两种处理以防万一。在两种情况下,升级都可以正常运行:

(venv) Files\app> flask db upgrade
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade 2177b1c9ee45 -> 6c61158ea270, empty message
(venv) Files\app>

但是当我使用Flask-SQLAlchemy在命令行上查询时:

>>> from app.models import Article
>>> arts = Article.query.all()
>>> arts[0]
<Example Article: "Title" (2018)>       ##(Valid __repr__ of the model)
>>> arts[0].time_added
datetime.datetime(2019, 12, 25, 9, 23, 43, 331296)    ##(achieved this by deleting and restarting db from scratch)
>>> arts[0].example
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Article' object has no attribute 'example'
>>>

我不知道升级有什么问题,但是一定有问题,因为降级给我一个错误:

INFO  [alembic.runtime.migration] Running downgrade 6c61158ea270 -> 2177b1c9ee45, empty message
Traceback (most recent call last):
  File "c:\desktop\projects\site\app\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
    cursor, statement, parameters, context
...
  File "c:\desktop\projects\site\app\venv\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "DROP": syntax error
[SQL: ALTER TABLE article DROP COLUMN example]

降级功能非常简单,因此绝不能创建该列:

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('article', 'example')
    # ### end Alembic commands ###

有人可以帮助我了解如何在Flask-migrate迁移脚本中使用Alembic来自定义数据库升级吗?

或者,我使用op.execute("UPDATE table SET column = values")的方式有问题吗?

谢谢!

编辑:

忘了,这是模型中的代码:

    example = db.Column(db.DateTime, default=datetime.utcnow())

此外,手动更改升级和降级也无效:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # ### end Alembic commands ###
    op.execute('UPDATE article SET example = datetime.utcnow()')

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute('UPDATE article SET example=Null')
    # ### end Alembic commands ###

附加编辑:

from app.models import set_time ### (set_time is just datetime.utcnow() but I
                                ### thought it might work to import it
                                ### from elsewhere -- it didn't

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # ### end Alembic commands ###
    op.execute("UPDATE 'article' SET 'example' = VALUES (?)", (set_time))  #*

### (*Importing set_time from elsewhere 

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("UPDATE 'article' SET 'example'=Null")
    # ### end Alembic commands ###

我一直收到此错误:

TypeError: execution_options() argument after ** must be a mapping, not str

似乎必须存在一种格式,用于将Python变量传递给我不知道的Alembic SQL查询。正在搜索。

另一个编辑(很抱歉,很多:):

以下内容仅告诉我article(表名)未定义。帮助语法?

connection = op.get_bind()

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # ### end Alembic commands ###
    connection.execute(
        article.update().values({"example": set_time})
    )

任何想法都非常感谢!

-Pete

我有一个小应用程序,正在使用它从在线文章中抓取数据。目前,我正在尝试找出如何从Flask-migrate编辑迁移脚本,这样就不必删除所有...

python flask flask-sqlalchemy alembic flask-migrate
1个回答
1
投票

如果迁移已经解决,您可以毫无问题地进行更新,但是尚未创建该列,我个人只是将其手动添加到sqlite数据库中,这样它就可以正常运行而不会出现问题,这些错误有时会在sqlite中发生。] >

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.