两个Python Flask App运行SQL Alchemy迁移命令时共享相同的数据库放置表问题

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

我已经构建了两个烧瓶应用程序,一个用于业务(APP 1),另一个用于管理员(APP 2)。 APP 1和APP 2共享相同的数据库和表,但APP 2使用的是与APP 1中不存在的少数与预订相关的表。现在的问题是,每当我在APP 1中执行SQL Alchemy migration命令时,它都会为预订表生成删除表语法因为这些表模型在APP 1中不存在。

使用SQL Alchemy迁移处理两个flask应用程序共享同一数据库的最佳方法是什么?

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

您可以在app1的alembic.ini文件中定义要排除在app1中的表,示例如下:

[alembic:exclude]
tables = table1,table2

然后在您的env.py文件中,您可以在include_object函数中。

include_object是一个可调用的函数,可以给任何对象返回True或False,指示是否应在自动生成扫描中考虑给定的对象。

https://alembic.sqlalchemy.org/en/latest/api/runtime.html?highlight=include_object#alembic.runtime.environment.EnvironmentContext.configure.params.include_object

env.py文件中的代码

exclude_tables = config.get_section('alembic:exclude').get('tables', '').split(',')


def include_object(object, name, type_, reflected, compare_to):
    if type_ == "table" and name in exclude_tables:
        return False
    else:
        return True

exclude_tables将包含您在alembic.ini文件中定义的所有表的列表

然后将context.configure函数中包含此include_object函数,如下所示:

context.configure(
    # ...
    include_object = include_object
)
© www.soinside.com 2019 - 2024. All rights reserved.