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.
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.
Predict and Run 10 min · Investigate 8 min · Modify and Make 20 min
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.
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.
Students colour the SQL inside the Python and explain which function reads and which function writes.
Remembering the order: open, run, commit, close. Write it as a four-line recipe on the board.
| What you will see | A question to ask | The fix |
|---|---|---|
| A member vanishes after Run. | Is there a commit after the INSERT? | Add conn.commit() before conn.close(). |
| sqlite3.OperationalError about a missing column | What 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. |
One possible solution for each task. Other correct programs are fine.
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()
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: Add a WHERE so a group page shows only one group's members.
Support: Give load_members and ask for the INSERT.
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.
Next: back to the Flask course, or on to the APIs lessons.