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

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

当前,我正在尝试找出如何从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

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

如果已经解决了迁移问题,但没有问题,但尚未创建该列,我个人将其手动添加到sqlite数据库中,这样它就可以正常运行而没有问题,sqlite有时会发生这些错误。

本文链接:https://www.f2er.com/2863339.html

大家都在问