python - Flask routing to functions with same name in different modules -
if have 2 files, e.g.:
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" and in __init__.py
from flask import flask import ipython import logging app = flask(__name__, static_url_path='', static_folder='static', template_folder='templates') mypackage import modulea, moduleb then flask throw error assertionerror: view function mapping overwriting existing endpoint function: get
i presume python doesn't see conflict here because functions in 2 separate modules, flask does. there better standard use here, or have make function names def getmodulea?
you use variable in route so, simpler solution if application doesn't need modularized:
@app.route('/module/<name>') def get(name): if name == 'a': return "a" else: return "b" else, need use blueprints if want have same url endpoints different functions of application. in both files, import 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" and in main app. file, can register these blueprints so:
from modulea import modulea moduleb import moduleb app = flask(__name__) app.register_blueprint(modulea) #give correct template & static url paths here app.register_blueprint(moduleb)
Comments
Post a Comment