我有一个连接到 PostgreSQL 数据库的 flask 应用程序。我集成了 celery 并将其结果后端配置为 相同 postgresql 数据库。
Celery automatically created two tables (Task and TaskSet) in the database.
flask 应用程序中使用的其他表在代码中具有类定义,并使用 alembic (flask-migrate) 生成:
$ flask db migrate -m "add a table" (creates migration file)
$ flask db upgrade (applies changes in migration file to the db)
问题
我在我的代码中为一个表添加了一个新类并运行了 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 表的类定义不存在于我的代码中,Alembic 试图删除它们。
我研究过是否可以覆盖 celery 对 Task 和 TaskSet 表的创建,以便我可以通过迁移手动创建表,但找不到任何文档。我查看了 database_table_name
和 database_table_schemas
配置属性,但看起来它们无法解决问题。 Celery docs.
问题:
有没有办法覆盖/继承 celery 创建的表,以便我可以通过迁移手动生成它们? 即我创建了一个继承 celery Task 表的自定义 Task 表,然后执行迁移以创建该表。
from celery.backends.database.models import Task from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class CustomTask(db.Model, Task): pass
我可以配置 alembic 以忽略由 celery 创建的表吗?
有没有更好的方法?我的方法可能完全不对
编辑:
看起来您可以指定在 alembic/flask-migrate 中忽略哪些表: Preserve existing tables in database when running Flask-Migrate
最佳答案
您可以使用 Alembic 的 include_object
选项单独保留 Celery 表。您仍将使用 Celery 来创建表。
- 文档:https://alembic.sqlalchemy.org/en/latest/api/runtime.html#alembic.runtime.environment.EnvironmentContext.configure.params.include_object
- 实例:Preserve existing tables in database when running Flask-Migrate
这通过防止 Alembic 在您每次自动生成新的数据库迁移时尝试删除 Celery 表来解决问题。但是,此解决方案不会将 Celery 表合并到您的数据库迁移存储库中。
解决该问题的第二种方法是将 Celery 表添加到您的 SQLAlchemy 配置中,可以作为模型类,也可以只是表。为此,您需要查看这些表的架构并将其复制到您的 SQLAlchemy 表或模型定义中。这将使这些表出现在数据库迁移中,因此它们将在您启动新数据库时随时重新创建。
关于python - Flask-migrate 删除由 Celery 创建的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65500719/