API 蓝图版本控制导致冲突

API versioning with blueprints causes colission

是时候为我的 api 发布一个新版本并且仍然支持以前的版本了。

我按照 的已接受答案中的说明进行操作。不幸的是,我没有足够的代表在该答案的评论中提问。

我的应用程序结构如下所示:

+-- app/
    +-- api_2_0/
        +-- __init__.py
        (...)
    +-- api_2_1/
        +-- __init__.py
        (...)
   +-- __init__.py

两者都是蓝图,我在 __init__.pycreate_app 方法中以这种方式初始化(​​我使用的是 app factory 方法):

def create_app(config_name):
    app = Flask(__name__)

    (...)

    from .api_2_0 import api as api_2_0_blueprint
    app.register_blueprint(api_2_0_blueprint, url_prefix='/api/v2.0')

    from .api_2_1 import api as api_2_1_blueprint
    app.register_blueprint(api_2_1_blueprint, url_prefix='/api/v2.1')

但这会导致:

AssertionError: A blueprint's name collision occurred between <flask.blueprints.Blueprint object at 0x7f8e48e82c10> and <flask.blueprints.Blueprint object at 0x7f8e48ef7150>.  Both share the same name "api".  Blueprints that are created on the fly need unique names.

的确,两者在它们的文件夹中都被称为 api,但我导入它们时使用了不同的名称。必须为每个版本将对 api 的所有调用重命名为其他名称会使版本控制变得痛苦并且总体上会造成代码混乱。

有更好的方法吗?

好的,事实证明我只需要更改蓝图定义即可。

在我将两个蓝图都定义为 api = Blueprint('api', __name__) 之前,这导致了冲突并让我认为我需要更改变量的名称 api

原来我真正需要更改的只是调用 Blueprint 时使用的字符串 'api',所以现在我的蓝图被定义为 api = Blueprint('api_2_0', __name__)api = Blueprint('api_2_1', __name__), 允许我在两种情况下保持变量 api 相同,并省去了到处修改它的问题。

我现在意识到这是一个非常愚蠢的问题,但我把它留在这里以防有人遇到同样的问题。