2017-09-11 77 views
0

如果我有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本身并没有在这里看到冲突,因为函数是在2个独立的模块中,但是烧瓶的确如此。有没有更好的标准在这里使用,或者我必须使功能名称如def getModuleA

回答

1

,你可以在你的路线,像这样,这是你的应用程序并不需要模块化的简单的解决方案使用变量:

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

否则,你需要使用blueprints,如果你想拥有相同的网址端点,但针对应用程序的不同功能。在这两个文件中,导入Blueprint。

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) 
1

您可以考虑使用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 
相关问题