🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Responses

A response is what a view returns. Flask turns the returned value into a page for the browser.

Make the app

This line makes the Flask app. The routes below belong to it.

from flask import Flask

app = Flask(__name__)

The home route

This route returns the welcome text.

@app.route("/")
def home():
    return "Welcome!"

The about route

This route returns its own page text.

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

Ask for both pages

The test client 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 "Welcome!"

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

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

Key points

  • A view returns text, and Flask sends it as the page.
  • One app holds many routes with many responses.
  • Each route returns its own page.
  • The test client reads the page from the response.

In this example, the app has two routes. Each view returns its own page text. The test client asks for each address and prints the page the app returns.

Note

A view must return text, a tuple, or a response object.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a view return to make a page?