2

Does the function name (adhoc_test) need to match the app.route path?

from flask import request

@app.route('/adhoc_test/')
def adhoc_test():

I'm not really sure of the internals, but what exactly is executing the function (of the same name), when the adhoc_test route/path is requested?

JackOfAll
  • 377
  • 1
  • 3
  • 13

2 Answers2

6

No, the name of the function does not matter (ie it does not have to match the route), as long as you do not have more than one function with the same name (then you will get an actual error when running the server)

AssertionError: View function mapping is overwriting an existing endpoint function

but what exactly is executing the function

It is a bit more complicated than that, but in the end of the day flask keeps a dictionary as a map between the "endpoint" (the function name) and the function object (which is the reason why function names must be unique):

self.view_functions[endpoint] = view_func

It also keeps a url_map to map routes to functions:

Map([<Rule '/route_a' (OPTIONS, GET, HEAD) -> func_a>,
     <Rule '/route_b' (OPTIONS, GET, HEAD) -> func_b>,
     <Rule '/static/<filename>' (OPTIONS, GET, HEAD) -> static>])
{}
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

No, you can name the function as you please.

Clearly it is also important naming your function wisely and this is one of the main reasons:

The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.

Here's an example of why using a relevant function name is very handy (url_for usage example):

from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}\'s profile'.format(username)

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

You can read this information other details in Flask's Documentation.

Pitto
  • 8,229
  • 3
  • 42
  • 51
  • 1
    The example is a bit misleading. The name of the method does not have to match the route, yet this answer leaves the impression that it does. `url_for` would work even the names do not match – DeepSpace Mar 11 '19 at 13:49
  • Well said. That is because matching routes and function names is just a good practice but the code would indeed work also with routes that are different from their relative function name (the /user/ can be used as example here) The key concept I wanted to underline in the code is that you'll need function names in other parts of the application, like the url_for. – Pitto Mar 11 '19 at 15:37