0

Is there any way, in Flask, to handle the issue of duplicate function names for views across files? Just to be clear, I'm talking about the name of the function, not the route defined for the function. So imagine in file1.py I've got:

@app.route('/some/unique/route')
def duplicateFunctionName():
   ...python code...

And then in file2.py I've got:

@app.route('/another/unique/route/name')
def duplicateFunctionName():
   ...python code...

And then in main.py I import these view functions:

import file1
import file2

<<code to run the flask server>>

The problem is that in large projects it's really hard to keep the function names unique. At some point you're bound to have two functions called def saveData() or whatever, and it's really hard to debug those issues. Is there an elegant solution to this problem?

1
  • Unless you're using from fileN import * the two functions will remain in their own namespaces as file1.duplicateFunctionName and file2.duplicateFunctionName. Commented Jun 25, 2014 at 18:24

1 Answer 1

1

There are two ways to solve this problem.

  1. Use the endpoint keyword argument to .route:

    @app.route('/some/unique/route', endpoint="unique_name_1")
    def duplicateFunctionName():
        pass
    
    @app.route('/another/unique/route', endpoint="unique_name_2")
    def duplicateFunctionName():
        pass
    

    This will ensure that all of your functions are addressable by url_for, etc. However, you will need to ensure that all of your endpoint names are unique, so it's not perfect.

  2. Use Blueprint's to split up your routes into smaller self-contained packages:

     bp1 = Blueprint("module_one", __name__)
    
     @bp1.route("/some/unique/route")
     def duplicateFunctionName():
         pass
    
     bp2 = Blueprint("module_two", __name__)
    
     @bp2.route("/another/unique/route")
     def duplicateFunctionName():
         pass
    

    The advantage here is that the endpoint name is prefixed with the name of the blueprint, which means that instead of having two endpoints with the conflicting name duplicateFunctionName you now have two endpoints with the names module_one.duplicateFunctionName and module_two.duplicateFunctionName.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.