Flask-migrate 删除由 Celery 创建的表

Flask-migrate drops tables created by Celery

我有一个连接到 PostgreSQL 数据库的烧瓶应用程序。我集成了 celery 并将其结果后端配置为 same postgresql 数据库。

Celery automatically created two tables (Task and TaskSet) in the database.

flask app中使用的其他table在代码中有class定义,使用alembic(flask-migrate)生成:

$ flask db migrate -m "add a table" (creates migration file)
$ flask db upgrade (applies changes in migration file to the db)

问题

我在我的代码中为 table 添加了一个新的 class 并且 运行 flask db migrate -m "add test table".

该命令生成一个迁移文件,这里是有问题的片段:

def upgrade():
    op.create_table('TestTable',
       sa.Column('id', sa.Integer(), nullable=False),
       sa.PrimaryKeyConstraint('id')
    )


    # DROP HERE
    op.drop_table('taskset')
    op.drop_table('task')

因为 celery 的 Task 和 Taskset table 的 class 定义不存在于我的代码中 Alembic 试图删除它们。

我研究过是否可以覆盖 celery 对 Task 和 TaskSet tables 的创建,以便我可以通过迁移手动创建 tables,但找不到任何文档。我查看了 database_table_namedatabase_table_schemas 配置属性,但看起来它们无法解决问题。 Celery docs.

问题:

  1. 有没有办法 override/inherit 芹菜创建的 table 以便我可以通过迁移手动生成它们? 即我创建了一个自定义任务 table 继承了芹菜任务 table 然后执行迁移以创建 table.

    from celery.backends.database.models import Task
    from flask_sqlalchemy import SQLAlchemy
    db = SQLAlchemy()
    
    class CustomTask(db.Model, Task):
        pass
    
  2. 我可以配置 alembic 以忽略由 celery 创建的 tables 吗?

  3. 有没有更好的方法?我的方法可能完全不对

编辑:

看来您可以指定在 alembic/flask-migrate 中忽略哪些 table: Preserve existing tables in database when running Flask-Migrate

您可以使用 Alembic 中的 include_object 选项单独保留 Celery table。您仍将使用 Celery 创建 tables.

这通过防止 Alembic 在您每次自动生成新的数据库迁移时尝试删除 Celery table 来解决问题。但是,此解决方案不会将 Celery table 合并到您的数据库迁移存储库中。

解决该问题的第二种方法是将 Celery table 添加到您的 SQLAlchemy 配置中,作为模型 类,或者只是 table。为此,您需要查看这些 table 的架构并将其复制到您的 SQLAlchemy table 或模型定义中。这将使这些 table 出现在数据库迁移中,因此它们将在您启动新数据库时随时重新创建。