2017-09-11 80 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 
相關問題