Flask Routes
A route is an address on a Flask site. Each route has a view function that returns the page for that address.
Make the app
This line makes the Flask app. Every route in the lesson belongs to it.
from flask import Flask
app = Flask(__name__)Add the home route
The decorator marks home as the answer for /. The function returns the home page text.
@app.route("/")
def home():
return "Home page"Add the about route
A second route works the same way. It answers /about with its own page text.
@app.route("/about")
def about():
return "About page"Ask the test client
The test client calls the app without a server. It asks for each address and prints the page it gets back.
client = app.test_client()
print(client.get("/").data.decode())
print(client.get("/about").data.decode())Example
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.route("/about")
def about():
return "About page"
client = app.test_client()
print(client.get("/").data.decode())
print(client.get("/about").data.decode())Key points
- A route pairs an address with a view function.
- The line @app.route("/") marks a function as the answer for the address /.
- A view function is an ordinary Python function that returns a page.
- One app holds many routes, one per address.
- Each route returns its own page.
In this example, the app is made first. Two routes follow: / returns "Home page" and /about returns "About page". The test client then asks for each address. The prints show the two pages the app returns.
Note
Route addresses start with a slash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line marks home as the answer for the address /?