Route URLs in Flask

One of the main features that Flask and what makes it very convenient and easy to use is the creation of routes. The idea behind it is that a route is defined and this route is assigned a method that responds for it.

In this way we can define the following route:

@app.route('/greeting/day')
def day():
  return "Good Morning!!!"

What we see is that the GET request on the URL ‘/saludo/dia’ will be answered by the functionality of the dia() method. As we can see, something very simple.

In the end we will end up creating an application in which all its routes are called from one to another, in the end, in most cases they will be web pages.

As everything is based on these routes we have to be especially careful when we use them. That is, we should not use the route directly but rather we should reference the method.

To be able to reference the method and return the route we have the url_for() operation. This operation receives the name of the method as a parameter and returns the route.

print url_for(method)

This will allow us to ensure that if we change a route the rest of the application will not be affected.

As an example we are going to create three routes:

@app.route('/greeting/day')
def day():
    return "Good Morning!!!"

@app.route('/greeting/afternoon')
def late():
    return "Good Afternoon!!!"

@app.route('/greeting/night')
def night():
    return "Good Night!!! May you rest!!!"

And now we are going to see how they would be referenced from a template in Flask:

  • {{ url_for(“day”) }}
  • {{ url_for(“late”) }}
  • {{ url_for(“night”) }}

In this way we have already seen the most correct way to handle Route URLs in Flask.

Leave a Comment