The time has come where I need to release a new version for my api and still support the previous one.
I followed the instructions given in the accepted answer for this question. Unfortunately I don't have enough rep to ask in the comments of that answer.
I have an app structure that looks like this:
+-- app/
+-- api_2_0/
+-- __init__.py
(...)
+-- api_2_1/
+-- __init__.py
(...)
+-- __init__.py
Both are blueprints which I initialize this way in my __init__.py
in the create_app
method (I'm using the app factory method):
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')
But this causes:
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.
It's true that both are called api
inside their folders but I'm importing them with different names. Having to rename all the calls to api
to something else for each version would make versioning painful and overall a code mess.
Is there a better way to do this?
答案 0 :(得分:1)
好的,事实证明我只需要更改蓝图定义。
在我将两个蓝图定义为导致碰撞的api = Blueprint('api', __name__)
之前,我认为我需要更改变量api
的名称。
原来我需要更改的只是调用'api'
时使用的字符串Blueprint
,所以现在我的蓝图定义为api = Blueprint('api_2_0', __name__)
和api = Blueprint('api_2_1', __name__)
,允许我在两种情况下保持变量api
相同,并省去了在任何地方进行变换的问题。
我现在意识到这是一个非常愚蠢的问题,但是如果有人遇到同样的问题,我会把它留在这里。