Elliot Woods
Elliot Woods

Reputation: 844

Flask routing to functions with same name in different modules

If I 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')
from MyPackage import moduleA, moduleB

Then flask will throw an error AssertionError: View function mapping is overwriting an existing endpoint function: get

I presume that python itself doesn't see a conflict here because the functions are in 2 separate modules, however flask does. Is there a better standard to use here, or do i have to make the function names like def getModuleA?

Upvotes: 5

Views: 4411

Answers (2)

Ivan Choo
Ivan Choo

Reputation: 2147

You can consider using 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.

Example:

# 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

Upvotes: 5

smundlay
smundlay

Reputation: 155

you could use a variable in your route like so, which is the simpler solution if your application doesn't need to be modularized:

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

Else, you need to use blueprints if you want to have the same url endpoints but for different functions of an 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 your main app. file, you can register these blueprints like so:

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)

Upvotes: 1

Related Questions