gpt4 book ai didi

python - Flask 路由到不同模块中具有相同名称的函数

转载 作者:行者123 更新时间:2023-11-28 22:24:43 26 4
gpt4 key购买 nike

如果我有 2 个文件,例如:

moduleA.py

from MyPackage import app

@app.route('/moduleA/get')
def get():
return "a"

moduleB.py

from MyPackage import app

@app.route('/moduleB/get')
def get():
return "b"

并在 __init__.py

from flask import Flask
import IPython
import logging

app = Flask(__name__,
static_url_path='',
static_folder='static',
template_folder='templates')
from MyPackage import moduleA, moduleB

然后flask会抛出错误AssertionError: View function mapping is overwriting an existing endpoint function: get

我认为 python 本身在这里没有看到冲突,因为函数在 2 个独立的模块中,但是 flask 有。有没有更好的标准可以在这里使用,还是我必须将函数名称命名为 def getModuleA

最佳答案

可以考虑使用Blueprint

Factor an application into a set of blueprints. This is ideal for larger applications; a project could instantiate an application object, initialize several extensions, and register a collection of blueprints.

例子:

# module_a.py
from flask import Blueprint

blueprint = Blueprint('module_a', __name__)

@blueprint.route('/get')
def get():
return 'a'

# module_b.py
from flask import Blueprint

blueprint = Blueprint('module_b', __name__)

@blueprint.route('/get')
def get():
return 'b'

# app.py
from flask import Flask
from module_a import blueprint as blueprint_a
from module_b import blueprint as blueprint_b


app = Flask(__name__)
app.register_blueprint(blueprint_a, url_prefix='/a')
app.register_blueprint(blueprint_b, url_prefix='/b')

# serves:
# - /a/get
# - /b/get

关于python - Flask 路由到不同模块中具有相同名称的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com