🎓 A1Learner
🔍
0 of 50 lessons completed

Building Flask URLs

url_for builds an address from a view function name. The address stays right even when the route changes.

Make the app with two routes

This app has a home route and an about route. The links route below points at them.

from flask import Flask, url_for

app = Flask(__name__)

@app.route("/")
def home():
    return "Home page"

@app.route("/about")
def about():
    return "About page"

Build the links

url_for takes each function name and returns its address. The view joins them into one line.

@app.route("/links")
def links():
    return "Home: " + url_for("home") + ", About: " + url_for("about")

Ask for the links

The test client asks for /links and prints the two built addresses.

client = app.test_client()
print(client.get("/links").data.decode())

Example

from flask import Flask, url_for

app = Flask(__name__)

@app.route("/")
def home():
    return "Home page"

@app.route("/about")
def about():
    return "About page"

@app.route("/links")
def links():
    return "Home: " + url_for("home") + ", About: " + url_for("about")

client = app.test_client()
print(client.get("/links").data.decode())

Key points

  • url_for("home") returns the address of the home route.
  • The argument is the function name as text.
  • Build links with url_for instead of writing addresses by hand.
  • A changed route needs no link edits.

In this example, the app has three routes. The links route calls url_for with each function name. url_for returns / for home and /about for about. The test client asks for /links and prints the two built addresses.

Note

url_for runs inside a view function.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does url_for("about") return for the route @app.route("/about")?