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.
Make your prediction first. Help opens once you've locked it in.
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])
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 |
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()
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?
Change load_members so the newest member is at the top of the list.
Before a hint: what kind of stuck is this? Try a strategy first
The order is in the SELECT in load_members.
Add DESC after ORDER BY id.
Show the newest member first.
Run your program. This ticks when your code does all of the above.
Add a page at /count that says how many members the club has. Let the database do the counting.
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.
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.
Lesson done. You've finished every step you need.
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.
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.
Remembering the order: open, run, commit, close. Write it as a four-line recipe on the board.
Stretch: Add a WHERE so a group page shows only one group's members.
Support: Give load_members and ask for the INSERT.
Next: back to the Flask course, or on to the APIs lessons.