← Teacher guide

Web apps with Flask: cheat sheet

Web apps with Flask · In any playground, open Reference to copy these.

Pages from Python

home

Go back to the centre, facing right.

home()
Example
forward(80)
left(90)
forward(40)
home()
What it draws
Back to the centre, facing right

variable

Give a value a name, so you can reuse and change it.

size = 50
Example
length = 120
forward(length)
left(90)
forward(length / 2)
What it draws
length = 120, then half of it

list

Keep many values in order under one name. The first item is place 0.

colours = ["red", "blue", "green"]

for each item

Work through a list, one item at a time.

for c in colours:
    pass
Example
pensize(6)
for c in ["red", "blue", "green"]:
    pencolor(c)
    forward(40)
What it draws
One line per colour in the list

join text

Join pieces of text into one with +. Spaces only appear where they are inside the quotes.

"Hello, " + name

dictionary value

The value stored under that key. The key goes in quotes. Assign to it to change it: star["speed"] = 8.

star["speed"]

in

True if the item is in the list (or the key is in the dictionary, or the letters are in the text).

if item in bag:
    pass

a page from a template

A template is HTML with gaps: {{ }} shows a value, {% for %} repeats a part for each item.

PAGE = """<ul>
{% for m in members %}
  <li>{{ m["name"] }}</li>
{% endfor %}
</ul>"""

return render_template_string(PAGE, members=members)

if / else

Do one thing or the other, depending on a condition.

if x > 0:
    pass
else:
    pass
Example
for x in [-90, -30, 30, 90]:
    penup()
    goto(x, 0)
    if x > 0:
        dot(30, "red")
    else:
        dot(30, "blue")
hideturtle()
What it draws
Red when x > 0, else blue

grow value

Change a value every pass: read the old one, store a new one.

size = 5
for i in range(20):
    forward(size)
    right(90)
    size = size + 5
Example
size = 5
for i in range(30):
    forward(size)
    right(90)
    size = size + 5
What it draws
The same spiral, grown by an update

def (function)

Name a group of steps, then run it by calling its name.

def shape():
    pass

shape()
Example
def zigzag():
    left(45)
    forward(30)
    right(90)
    forward(30)
    left(45)

zigzag()
zigzag()
zigzag()
What it draws
Defined once, called three times

a Flask route

Joins an address to a function. What the function returns is the page.

@app.route("/about")
def about():
    return "<h1>About</h1>"

an address with a part that changes

<name> matches any word in that place of the address, and is passed to the function.

@app.route("/group/<name>")
def group(name):
    return "You asked for  + name

Forms and saving

print

Show text or a value in the output box.

print("Hello")

write a file

"w" makes the file, or empties it first if it is already there, then writes. with closes the file at the end.

with open("save.txt", "w") as f:
    f.write(text)

read a CSV

Each row of the file becomes a dictionary, keyed by the column names in the first line. Every value is text.

import csv

with open("music.csv") as f:
    rows = list(csv.DictReader(f))

go to another page

Sends the browser on to another address, such as back home after a form.

return redirect("/")

strip and lower

strip() removes spaces at the ends; lower() and upper() change the capitals. Each gives back new text.

command = command.strip().lower()

read a file

Opens the file to read and gives you all of it as one piece of text.

with open("save.txt") as f:
    text = f.read()

read a form

A form with method='post' sends each box that has a name='...' attribute. request.form looks them up by that name.

@app.route("/join", methods=["POST"])
def join():
    name = request.form["name"].strip()

add a row to a CSV

"a" adds to the end of the file instead of emptying it. Each list becomes one row.

with open("members.csv", "a", newline="") as f:
    csv.writer(f).writerow([name, group])

APIs

send JSON

Return a dictionary and Flask sends it as JSON, for other programs to read.

@app.route("/api/members")
def api_members():
    return {"members": members}

a FastAPI route

The type after each parameter (int, str, float) is checked: a wrong value gets an error reply (422) before your code runs.

@api.get("/year")
def year(y: int):
    return {"next": y + 1}