← Web apps with Flask

Web apps with Flask: recap

For after the lessons: one card per lesson, to check what you remember. Answer each question in your head or on paper first, then check it. Nothing here is marked.

Pages from Python

1. A page from Python

Try firstWhat is a route?

Check your answer

A link between an address in the site, such as /about, and the Python function that makes that page.

  1. @app.route("/") joins the address / to the function below it.
  2. When someone visits an address, Flask runs its function and sends back what it returns, as the page.
  3. An address with no route gets a 404 Not Found page.
Each route joins an address to a function; the function's return is the page · Sound on for the voiceover
Open the lesson →

2. Pages from data

Try firstWhat does {% for p in players %} do in a template?

Check your answer

Repeats the part up to {% endfor %} once for each item in players, with p as that item.

  1. A template is HTML with gaps: {{ }} shows a value and {% for %} repeats a part for each item.
  2. render_template_string(PAGE, players=players) fills the gaps with the data passed to it.
  3. /player/<name> matches any name in that place of the address and passes it to the function.
Open the lesson →

Forms and saving

3. Join the club

Try firstA form box has id="name" but no name attribute. What does the server get from it?

Check your answer

Nothing: only boxes with a name attribute are sent, under that name.

  1. method="post" action="/join" sends the form to /join; each box with a name is sent under that name.
  2. The /join route reads them with request.form["name"] and adds the member.
  3. redirect("/") sends the browser back home, where the list now has the new member.
Open the lesson →

4. Keep the sign-ups

Try firstWhy does the app read members.csv for every page?

Check your answer

The file changes when people join, so reading it each time means the page always shows the current members.

  1. Joining adds a row to the end of members.csv with open(..., "a") and csv.writer.
  2. The home page reads the whole file every time, so new members show straight away.
  3. The data is in a file, not a variable, so it lasts when the app stops and starts again.
Open the lesson →

APIs

5. An API for the club

Try firstHow is an API route different from a page route?

Check your answer

It sends data (JSON) for a program to use, instead of an HTML page for a person to read.

  1. A route that returns a dictionary sends it as JSON: data for programs, not a page for people.
  2. /api/members/<group> picks the matching members from the file and sends them with a count.
  3. Another program can read the JSON straight back into a dictionary or list.
Open the lesson →