← Teacher guide Markdown for Prepare

Forms and saving: cheat sheet

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

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])