Flask Route Variables
A route variable is a part of the address that changes. The value arrives in the view function as an argument.
Make the app
This line makes the Flask app. The route below belongs to it.
from flask import Flask
app = Flask(__name__)Add a variable route
The part <name> catches one part of the address. It arrives in hello as the argument name.
@app.route("/hello/<name>")
def hello(name):
return "Hello, " + name + "!"Ask for two names
The same route answers both addresses. Each address prints its own greeting.
client = app.test_client()
print(client.get("/hello/Ana").data.decode())
print(client.get("/hello/Bo").data.decode())Example
from flask import Flask
app = Flask(__name__)
@app.route("/hello/<name>")
def hello(name):
return "Hello, " + name + "!"
client = app.test_client()
print(client.get("/hello/Ana").data.decode())
print(client.get("/hello/Bo").data.decode())Key points
- <name> in a route catches one part of the address.
- The part arrives as the argument with the same name.
- The view uses the value to build the page.
- One route answers many addresses this way.
In this example, the route /hello/<name> catches the last part of the address. The part arrives as the argument name. The view joins it into a greeting. The test client asks for two names, and each print shows the greeting for that name.
Note
A variable catches one part only, never a slash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does /hello/<name> catch from /hello/Ana?