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

时间:2017-09-11 09:56:46

标签: python flask

如果我有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

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

我认为python本身并没有在这里看到冲突,因为函数在两个独立的模块中,但是烧瓶确实如此。有没有更好的标准在这里使用,或者我必须使函数名称如def getModuleA

2 个答案:

答案 0 :(得分:2)

您可以考虑使用Blueprint

  

将应用程序视为一组蓝图。这是理想的选择   更大的应用;项目可以实例化一个应用程序   对象,初始化几个扩展,并注册一个集合   蓝图。

示例:

# 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

答案 1 :(得分:1)

你可以在你的路线中使用一个变量,如果您的应用程序不需要模块化,这是一个更简单的解决方案:

@app.route('/module/<name>')
def get(name):
   if name == 'a':
      return "a"
   else:
      return "b"

否则,如果您想拥有相同的url端点但需要使用不同的应用程序功能,则需要使用blueprints。在这两个文件中,导入蓝图。

from flask import Blueprint

<强> moduleA.py

moduleA = Blueprint('moduleA', __name__,
                        template_folder='templates')

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

<强> moduleB.py

moduleB = Blueprint('moduleB', __name__,
                        template_folder='templates')

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

并在您的主应用程序中。文件,您可以像这样注册这些蓝图:

from moduleA import moduleA
from moduleB import moduleB
app = Flask(__name__)
app.register_blueprint(moduleA) #give the correct template & static url paths here too 
app.register_blueprint(moduleB)
相关问题