← Teacher guide

Keep the club in a database

Students move the club app from a CSV file to a SQLite database file: CREATE TABLE IF NOT EXISTS, SELECT to read, INSERT with ? and commit to save.

Web apps with Flask · A database behind the app · about 40 minutes · Open the student lesson

Classroom resources

Open these in Waypoints Prepare with one click. To share a file another way, copy its address and paste it into Load URL, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.

Students will be able to

Timing

Predict and Run 10 min · Investigate 8 min · Modify and Make 20 min

Before class

This is an optional extension. Students should have done SQL lessons 1 to 8 (SELECT, WHERE, INSERT) and Keep the sign-ups. club.db is a real SQLite file kept in the browser with the course's other files, so it survives Run and a reload. It cannot be read in the Files tab. group is a reserved word in SQL, hence the column team. The Make step asks the database to count, which is the point: SQL finds, Python shows.

Running the lesson

  1. Predict: it is the memory database, so the answer is the same every run.
  2. Run: join twice, press Run, reload. The members are still there.
  3. Investigate: take the commit line out and show that the member disappears. Ask why.
  4. Make: students reuse the db() helper. A function that opens, runs and closes is the pattern.

In class

On the slides at these points. Students can do the whole lesson on their own; these are for the room. In the deck, the Run, Modify and Make slides have the live playground in them (the tutorial link is the backup), and the notes above are in each slide's speaker notes.

The hard part (on purpose)

Remembering the order: open, run, commit, close. Write it as a four-line recipe on the board.

When students get stuck

What you will seeA question to askThe fix
A member vanishes after Run.Is there a commit after the INSERT?Add conn.commit() before conn.close().
sqlite3.OperationalError about a missing columnWhat is the column called in the table?The column is team, not group. group is reserved in SQL.
The table already exists with the old columns.Did you change the CREATE TABLE after the first Run?Delete club.db in the Files tab and run again.

Answers to the checks

  1. Predict: What does it print?
    2. Each INSERT adds a row, and COUNT(*) counts them. The database here lives in memory, so it starts empty every time.
  2. The missing line: A member joins but is gone after Run. The INSERT line is there. What is missing?
    conn.commit() after the INSERT
    An INSERT changes the database in memory. commit() writes it into club.db.
  3. Passing the values: Why is the name passed as (name, team) after the query, not joined into it?
    So typed text stays a value, never SQL
    With ?, what a person types is always a value and can never change the SQL. A name like Robert'); DROP TABLE members;-- is just a name when it is passed separately.

Solutions

One possible solution for each task. Other correct programs are fine.

Modify

import sqlite3
from flask import Flask, render_template_string, request, redirect

app = Flask(__name__)
PAGE = """<h1>Chess club</h1>
<h2>Members</h2>
<ul>
{% for m in members %}
  <li>{{ m["name"] }} ({{ m["team"] }})</li>
{% endfor %}
</ul>
<h2>Join the club</h2>
{% if error %}<p style="color: crimson">{{ error }}</p>{% endif %}
<form method="post" action="/join">
  <label for="name">Name</label>
  <input id="name" name="name">
  <label for="group">Group</label>
  <select id="group" name="group">
    <option>Beginners</option>
    <option>Players</option>
    <option>Champions</option>
  </select>
  <button>Join</button>
</form>"""


def db():
    conn = sqlite3.connect("club.db")
    conn.row_factory = sqlite3.Row
    conn.execute("CREATE TABLE IF NOT EXISTS members (id INTEGER PRIMARY KEY, name TEXT, team TEXT)")
    return conn


def load_members():
    conn = db()
    rows = conn.execute("SELECT name, team FROM members ORDER BY id DESC").fetchall()
    conn.close()
    return rows


def save_member(name, team):
    conn = db()
    conn.execute("INSERT INTO members (name, team) VALUES (?, ?)", (name, team))
    conn.commit()
    conn.close()


@app.route("/")
def home():
    return render_template_string(PAGE, members=load_members())


@app.route("/join", methods=["POST"])
def join():
    name = request.form["name"].strip()
    group = request.form["group"]
    if name == "":
        return render_template_string(PAGE, members=load_members(), error="Please type your name.")
    save_member(name, group)
    return redirect("/")


app.run()

Make

import sqlite3
from flask import Flask, render_template_string, request, redirect

app = Flask(__name__)
PAGE = """<h1>Chess club</h1>
<h2>Members</h2>
<ul>
{% for m in members %}
  <li>{{ m["name"] }} ({{ m["team"] }})</li>
{% endfor %}
</ul>
<h2>Join the club</h2>
{% if error %}<p style="color: crimson">{{ error }}</p>{% endif %}
<form method="post" action="/join">
  <label for="name">Name</label>
  <input id="name" name="name">
  <label for="group">Group</label>
  <select id="group" name="group">
    <option>Beginners</option>
    <option>Players</option>
    <option>Champions</option>
  </select>
  <button>Join</button>
</form>"""


def db():
    conn = sqlite3.connect("club.db")
    conn.row_factory = sqlite3.Row
    conn.execute("CREATE TABLE IF NOT EXISTS members (id INTEGER PRIMARY KEY, name TEXT, team TEXT)")
    return conn


def load_members():
    conn = db()
    rows = conn.execute("SELECT name, team FROM members ORDER BY id").fetchall()
    conn.close()
    return rows


def save_member(name, team):
    conn = db()
    conn.execute("INSERT INTO members (name, team) VALUES (?, ?)", (name, team))
    conn.commit()
    conn.close()


@app.route("/")
def home():
    return render_template_string(PAGE, members=load_members())


@app.route("/join", methods=["POST"])
def join():
    name = request.form["name"].strip()
    group = request.form["group"]
    if name == "":
        return render_template_string(PAGE, members=load_members(), error="Please type your name.")
    save_member(name, group)
    return redirect("/")


@app.route("/count")
def count():
    conn = db()
    n = conn.execute("SELECT COUNT(*) FROM members").fetchone()[0]
    conn.close()
    return str(n) + " members"


app.run()

Stretch and support

Stretch: Add a WHERE so a group page shows only one group's members.

Support: Give load_members and ask for the INSERT.

Exit ticket

Why does a web app use a database instead of reading a file?

The database finds and changes just the rows needed, can be asked questions in SQL, and keeps working as the data grows.

What each step is for

Where it leads

Next: back to the Flask course, or on to the APIs lessons.