← Web apps with Flask

Keep the club in a database

Move the club's members from a CSV file into a SQLite database, so the app asks for exactly the rows it needs.

A file is read from the top every time. A database finds the rows you ask for.

This lesson swaps the CSV file for a database, using the SQL from the SQL course (lessons 1 to 8 first, please). The app looks almost the same. Only three functions change: one opens the database, one reads the members with a SELECT, and one adds a member with an INSERT.

The database is a file called club.db. It stays between Runs and reloads, like members.csv did. Open the Files tab to see it (it is not text, so it shows as a file you cannot read).

One new detail: group is a reserved word in SQL, so the column is called team.

How this lesson works: Predict, Run, Investigate, Modify, Make
PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

club.py
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE members (name TEXT)")
conn.execute("INSERT INTO members VALUES ('Ada')")
conn.execute("INSERT INTO members VALUES ('Sam')")
print(conn.execute("SELECT COUNT(*) FROM members").fetchone()[0])
What does it print?

RunRun it and compare the result with your prediction.

Run

Join a few members, then press Run and reload. They are still there, now stored in club.db.

Part What it does
sqlite3.connect("club.db") Opens the database file, making it the first time
CREATE TABLE IF NOT EXISTS Makes the table once, and does nothing after that
SELECT name, team FROM members Reads the rows the page needs
INSERT ... VALUES (?, ?) Adds a member. The two values go in separately
conn.commit() Saves the change into the file
club.py
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.run()
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

club.py
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.run()

What makes a change last?

Where does the typed text end up?

A member joins but is gone after Run. The INSERT line is there. What is missing?

Why is the name passed as (name, team) after the query, not joined into it?

ModifyChange the code on purpose and check the result.

Modify

Change load_members so the newest member is at the top of the list.

Try it yourselfYour edits are saved in this browser.
Build up to it
Which query gives the newest member first, if ids go up as members join?

Need a hint?

Before a hint: what kind of stuck is this? Try a strategy first

The order is in the SELECT in load_members.

Another hint

Add DESC after ORDER BY id.

Show the newest member first.

    Run your program. This ticks when your code does all of the above.

    MakeBuild something new using what you have learned. Expect a few tries; that is normal.

    Make

    Add a page at /count that says how many members the club has. Let the database do the counting.

    Try it yourselfYour edits are saved in this browser.
    Need a hint?

    Before a hint: what kind of stuck is this? Try a strategy first

    Open the database, run SELECT COUNT(*) FROM members, and return the number as text.

    Another hint

    conn.execute("SELECT COUNT(*) FROM members").fetchone()[0] gives the number.

    Add a /count page that shows how many members the club has, using COUNT(*).

      Run your program. This ticks when your code does all of the above.

      Now you can
      Finished the course?Go over it: Web apps with Flask recapEvery idea in one place, to check you've got it.You reached the endBack to Web apps with Flask
      For teachers

      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. About 40 minutes.

      Open the teacher guide: answers, solutions, slides and a worksheet.

      Students will be able to

      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.

      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

      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.

      Where it leads

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

      What each step is for