Objectives: LO-17.1, LO-17.2, LO-17.3
Prerequisites: the Module 17 reading and
Lab 16
Time: about 2 hours
In this lab you predict what a transaction keeps, build and query a table of rain readings,
break a query with SQL injection and then fix it, fetch JSON from a web API with retries, and
test the API code without a working server. Each exercise ends with a check cell that prints
passed or says what is wrong.
Setup¶
Run the next cell first. It starts a small weather API, like the reading’s, on a free port of
this computer, in a thread of its own, so it answers while the rest of the notebook runs.
BASE is its address. It knows the stations Harbor, Hilltop, Mill Lane, and Broken,
whose data is damaged, so the server answers 500. /flaky/<name> answers 503 twice for each
name, then 200. ?delay= makes it wait before answering, and requests_seen lists the path of
every request it gets.
The cell also sets the environment variable LAB17_KEY to the API’s key, as you would in a
terminal before starting a program. The databases in this lab live in memory, so the lab
writes no files.
import json
import os
import socket
import sqlite3
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest.mock import patch
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, quote, unquote, urlsplit
from urllib.request import Request, urlopen
import pytest
print("Python", sys.version.split()[0], "with SQLite", sqlite3.sqlite_version)
LAB_KEY = "lab17-demo-key"
STATIONS = {
"Harbor": [("2026-11-02", 1.2), ("2026-11-03", 0.0), ("2026-11-04", 7.4)],
"Hilltop": [("2026-11-02", 3.1), ("2026-11-03", 0.4), ("2026-11-04", 9.8)],
"Mill Lane": [("2026-11-02", 0.8), ("2026-11-03", 0.0), ("2026-11-04", 6.6)],
}
READINGS = [
(station, day, rain) for station, readings in STATIONS.items() for day, rain in readings
]
requests_seen = []
flaky_answers = {}
server_sleep = time.sleep # The server's own name for it, which patching time.sleep won't change.
class LabAPI(BaseHTTPRequestHandler):
"""The lab's weather API."""
def do_GET(self):
url = urlsplit(self.path)
query = parse_qs(url.query)
requests_seen.append(url.path)
server_sleep(float(query.get("delay", ["0"])[0]))
parts = [unquote(part) for part in url.path.strip("/").split("/")]
if self.headers.get("X-API-Key") != LAB_KEY:
self.reply(401, {"error": "missing or wrong API key"})
elif parts == ["stations"]:
self.reply(200, {"stations": sorted(STATIONS)})
elif parts == ["stations", "Broken"]:
self.reply(500, {"error": "this station's data is damaged"})
elif len(parts) == 2 and parts[0] == "stations" and parts[1] in STATIONS:
readings = [{"day": day, "rain_mm": rain} for day, rain in STATIONS[parts[1]]]
self.reply(200, {"name": parts[1], "readings": readings})
elif len(parts) == 2 and parts[0] == "flaky":
flaky_answers[parts[1]] = flaky_answers.get(parts[1], 0) + 1
if flaky_answers[parts[1]] <= 2:
self.reply(int(query.get("status", ["503"])[0]), {"error": "busy; try again"})
else:
self.reply(200, {"answer": flaky_answers[parts[1]]})
else:
self.reply(404, {"error": f"nothing at {url.path}"})
def reply(self, status, data):
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
try:
self.wfile.write(body)
except ConnectionError:
pass
def log_message(self, format, *args):
pass # Keep the notebook quiet: requests_seen records the requests instead.
server = ThreadingHTTPServer(("127.0.0.1", 0), LabAPI)
threading.Thread(target=server.serve_forever, daemon=True).start()
BASE = f"http://127.0.0.1:{server.server_address[1]}"
os.environ["LAB17_KEY"] = LAB_KEY
print("The lab's API is at", BASE)1. What a transaction keeps¶
Read this code, but don’t run it yet. quantity >= 0 is a constraint, so no row may hold a
negative quantity. quantity - 1 in an UPDATE uses each row’s own value.
db = sqlite3.connect(":memory:")
db.execute(
"CREATE TABLE stock (item TEXT PRIMARY KEY, quantity INTEGER NOT NULL CHECK (quantity >= 0))"
)
with db:
db.executemany("INSERT INTO stock VALUES (?, ?)", [("pens", 12), ("pads", 3), ("tape", 0)])
with db:
changed = db.execute(
"UPDATE stock SET quantity = quantity - 1 WHERE quantity > ?", (2,)
).rowcount
try:
with db:
db.execute("UPDATE stock SET quantity = quantity + 10 WHERE item = ?", ("tape",))
db.execute("UPDATE stock SET quantity = quantity - 5 WHERE item = ?", ("pads",))
except sqlite3.IntegrityError:
pass
final = db.execute("SELECT item, quantity FROM stock ORDER BY item").fetchall()
glue = db.execute("SELECT quantity FROM stock WHERE item = ?", ("glue",)).fetchone()
db.close()Exercise L17.1 (LO-17.1, ★, about 10 minutes)¶
Predict the value of each name: p1 for changed, p2 for final, and p3 for glue.
p1 = 0
p2 = []
p3 = "..."db = sqlite3.connect(":memory:")
db.execute(
"CREATE TABLE stock (item TEXT PRIMARY KEY, quantity INTEGER NOT NULL CHECK (quantity >= 0))"
)
with db:
db.executemany("INSERT INTO stock VALUES (?, ?)", [("pens", 12), ("pads", 3), ("tape", 0)])
with db:
changed = db.execute(
"UPDATE stock SET quantity = quantity - 1 WHERE quantity > ?", (2,)
).rowcount
try:
with db:
db.execute("UPDATE stock SET quantity = quantity + 10 WHERE item = ?", ("tape",))
db.execute("UPDATE stock SET quantity = quantity - 5 WHERE item = ?", ("pads",))
except sqlite3.IntegrityError:
pass
final = db.execute("SELECT item, quantity FROM stock ORDER BY item").fetchall()
glue = db.execute("SELECT quantity FROM stock WHERE item = ?", ("glue",)).fetchone()
db.close()
print(changed, final, glue)assert p1 == 2, "p1: rowcount counts the rows the UPDATE changed: every row with more than 2."
assert p2 == [("pads", 2), ("pens", 11), ("tape", 0)], (
"p2: the failed block rolls back both of its updates, the one that worked included."
)
assert p3 is None, "p3: fetchone returns None when no row matches."
print("passed")2. A table of readings¶
Exercise L17.2 (LO-17.1, ★★, about 20 minutes)¶
Write two functions:
create_readings(connection)creates a table namedreadingswith anidthat SQLite fills in, and three columns that must all have a value:station, text;day, text, such as"2026-11-02"; andrain_mm, a float (REALin SQLite) that can’t be negative. Add the lineUNIQUE (station, day)after the columns, which refuses a second reading for the same station on the same day.add_readings(connection, rows)adds the readings inrows, an iterable of(station, day, rain_mm)tuples, in one transaction: either every reading is saved, or, if any is refused, none is, and the exception reaches the caller.
def create_readings(connection):
"""Create the readings table."""
...
def add_readings(connection, rows):
"""Add (station, day, rain_mm) readings, all of them or none."""
...def fresh():
"""Return a database in memory with an empty readings table."""
connection = sqlite3.connect(":memory:")
create_readings(connection)
return connection
def count_rows(connection):
return connection.execute("SELECT COUNT(*) FROM readings").fetchone()[0]
connection = fresh()
add_readings(connection, [("Harbor", "2026-11-02", 1.2), ("Hilltop", "2026-11-02", 3.1)])
assert count_rows(connection) == 2, f"Expected 2 rows, found {count_rows(connection)}."
assert not connection.in_transaction, "add_readings should commit: use a with block."
row = connection.execute("SELECT * FROM readings WHERE station = 'Hilltop'").fetchone()
assert row == (2, "Hilltop", "2026-11-02", 3.1), (
f"Got {row}: the columns should be id, station, day, and rain_mm, in that order."
)
for bad, why in [
(("Harbor", "2026-11-03", -0.5), "a negative rain_mm"),
(("Harbor", "2026-11-02", 0.0), "a second reading for Harbor on 2026-11-02"),
((None, "2026-11-03", 1.0), "a reading with no station"),
(("Harbor", None, 1.0), "a reading with no day"),
(("Harbor", "2026-11-03", None), "a reading with no rain_mm"),
]:
try:
add_readings(connection, [("Mill Lane", "2026-11-05", 2.0), bad])
except sqlite3.IntegrityError:
pass
else:
raise AssertionError(f"The table should refuse {why}.")
assert count_rows(connection) == 2, (
f"After refusing {why}, the reading before it in the same call should be gone too."
)
add_readings(connection, ((f"Station {n}", "2026-11-02", n / 10) for n in range(5)))
assert count_rows(connection) == 7, "add_readings should accept any iterable, a generator too."
connection.close()
print("passed")3. Questions and corrections¶
SUM(rain_mm) adds up a column over the rows in each group, as COUNT(*) counts them, and a
WHERE condition can join two conditions with AND.
Exercise L17.3 (LO-17.1, ★★, about 20 minutes)¶
Write two functions, using your readings table:
rain_by_station(connection)returns a dictionary that maps each station to its total rainfall, rounded to one decimal place, in alphabetical order of station. Let the database do the adding up, withGROUP BY.correct_reading(connection, station, day, rain_mm)changes one reading’srain_mm, and saves the change. If no reading matches the station and the day, it raisesLookupErrorwith a message that names both.
def rain_by_station(connection):
"""Return each station's total rainfall, in mm, rounded to one decimal place."""
...
def correct_reading(connection, station, day, rain_mm):
"""Change one reading's rain_mm, or raise LookupError if there is no such reading."""
...connection = fresh()
add_readings(connection, READINGS)
totals = rain_by_station(connection)
assert totals == {"Harbor": 8.6, "Hilltop": 13.3, "Mill Lane": 7.4}, f"Got {totals}."
assert list(totals) == sorted(totals), "List the stations in alphabetical order: ORDER BY."
add_readings(connection, [("Hilltop", "2026-11-05", 0.1), ("Hilltop", "2026-11-06", 0.2)])
assert rain_by_station(connection)["Hilltop"] == 13.6, "Round each total to one decimal place."
empty = fresh()
empty_totals = rain_by_station(empty)
empty.close()
assert empty_totals == {}, f"An empty table has no stations, not {empty_totals}."
correct_reading(connection, "Harbor", "2026-11-04", 7.9)
value = connection.execute(
"SELECT rain_mm FROM readings WHERE station = 'Harbor' AND day = '2026-11-04'"
).fetchone()[0]
assert value == 7.9, f"Harbor's reading on 2026-11-04 should now be 7.9, not {value}."
assert not connection.in_transaction, "correct_reading should commit its change."
assert rain_by_station(connection)["Hilltop"] == 13.6, "Change only the one reading."
with pytest.raises(LookupError, match="Harbor") as caught:
correct_reading(connection, "Harbor", "2026-12-25", 1.0)
assert "2026-12-25" in str(caught.value), "Name the day in the message too."
with pytest.raises(sqlite3.IntegrityError):
correct_reading(connection, "Harbor", "2026-11-02", -1.0)
assert not connection.in_transaction, "A refused correction should be rolled back."
connection.close()
print("passed")4. SQL injection¶
This cell makes a table of readings of its own, and a function that builds its query with an f-string. Don’t copy the function.
def readings_for_unsafe(connection, station):
"""Return (day, rain_mm) for each of a station's readings. Unsafe."""
query = f"SELECT day, rain_mm FROM readings WHERE station = '{station}' ORDER BY day"
return connection.execute(query).fetchall()
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE readings (station TEXT, day TEXT, rain_mm REAL)")
with connection:
connection.executemany(
"INSERT INTO readings VALUES (?, ?, ?)", READINGS + [("St. Mary's", "2026-11-02", 2.2)]
)
print(readings_for_unsafe(connection, "Harbor"))Exercise L17.4 (LO-17.1, ★★, about 15 minutes)¶
Set
attackto a station name that makesreadings_for_unsafereturn every reading in the table. Write the query the f-string builds with your name on paper first.Write
readings_for(connection, station), which returns the same results for an honest name, but uses a placeholder, so thatattackfinds no readings and"St. Mary's"finds its own.
attack = "..."
def readings_for(connection, station):
"""Return (day, rain_mm) for each of a station's readings, in order of day."""
...everything = connection.execute("SELECT day, rain_mm FROM readings ORDER BY day").fetchall()
assert sorted(readings_for_unsafe(connection, attack)) == sorted(everything), (
"attack: close the quotation mark the f-string opens, then add a condition that is always "
"true, and leave the last quotation mark for the f-string to close."
)
assert readings_for(connection, "Harbor") == readings_for_unsafe(connection, "Harbor"), (
"readings_for should give the same results as the unsafe version for an honest name."
)
assert readings_for(connection, attack) == [], "With a placeholder, attack is only a strange name."
assert readings_for(connection, "St. Mary's") == [("2026-11-02", 2.2)], (
"An apostrophe in a name should be no problem with a placeholder."
)
connection.close()
print("passed")5. Fetching JSON¶
A program reads its API key from the environment, never from its own code:
key = os.environ["LAB17_KEY"]Exercise L17.5 (LO-17.2, ★★, about 15 minutes)¶
Write two functions for the lab’s API:
get_json(url, key, timeout=2.0)requestsurlwith the headersAccept: application/jsonandX-API-Key: <key>, waits at mosttimeoutseconds, and returns the body’s JSON. It lets every exception fromurlopenreach the caller.fetch_station(base_url, name, key)returns the JSON for{base_url}/stations/<name>, with the name quoted for the URL. It returnsNonefor a 404, raisesPermissionErrorwith a message about the key for a 401, and lets every other error reach the caller.
def get_json(url, key, timeout=2.0):
"""Return the JSON at url, sending key in the X-API-Key header."""
...
def fetch_station(base_url, name, key):
"""Return a station's JSON, None if there is no such station, or raise."""
...listing = get_json(f"{BASE}/stations", key)
assert listing == {"stations": ["Harbor", "Hilltop", "Mill Lane"]}, f"Got {listing}."
mill = fetch_station(BASE, "Mill Lane", key)
assert mill is not None and mill["name"] == "Mill Lane", "Quote the name: a URL can't hold a space."
assert requests_seen[-1] == "/stations/Mill%20Lane", f"The request went to {requests_seen[-1]}."
assert fetch_station(BASE, "Nowhere", key) is None, "A 404 means no such station: return None."
with pytest.raises(PermissionError):
fetch_station(BASE, "Harbor", "not-the-key")
with pytest.raises(HTTPError) as caught:
fetch_station(BASE, "Broken", key)
assert caught.value.code == 500, "Let other errors, such as a 500, reach the caller."
start = time.perf_counter()
with pytest.raises(TimeoutError):
get_json(f"{BASE}/stations?delay=1", key, timeout=0.2)
assert time.perf_counter() - start < 0.9, "Pass timeout on to urlopen."
print("passed")6. Trying again¶
A 429 (Too Many Requests) or a 503 (Service Unavailable), a refused connection, and a timeout can all go away if the program waits and tries again. Waiting longer after each failure, which is called backoff, gives a struggling service room to recover. Every other error will be the same next time.
Exercise L17.6 (LO-17.2, ★★★, about 20 minutes)¶
Write get_with_retries(url, key, attempts=3, wait=1.0, timeout=2.0), which calls your
get_json up to attempts times:
It returns the JSON as soon as an attempt succeeds.
After an
HTTPErrorwith the status 429 or 503, aURLError, or aTimeoutError, it callstime.sleepand tries again:waitseconds after the first failure, twice as long after the second, and so on. After the last attempt, it raises that attempt’s exception, without sleeping first.Any other
HTTPErrorit raises at once, without trying again.
Remember that HTTPError is a subclass of URLError.
def get_with_retries(url, key, attempts=3, wait=1.0, timeout=2.0):
"""Return the JSON at url, trying again after errors that might go away."""
...def requests_to(path):
return requests_seen.count(path)
with patch("time.sleep") as sleep:
answer = get_with_retries(f"{BASE}/flaky/a", key, attempts=3, wait=0.5)
assert answer == {"answer": 3}, f"Got {answer}: /flaky/a answers on the third attempt."
assert [c.args[0] for c in sleep.call_args_list] == [0.5, 1.0], (
f"Sleep 0.5 s, then 1.0 s; got {[c.args for c in sleep.call_args_list]}."
)
with patch("time.sleep") as sleep, pytest.raises(HTTPError) as caught:
get_with_retries(f"{BASE}/flaky/b?status=429", key, attempts=2, wait=0.5)
assert caught.value.code == 429 and requests_to("/flaky/b") == 2, (
"With attempts=2, raise the second 429."
)
assert sleep.call_count == 1, "Don't sleep after the last attempt."
for path, status in [("/stations/Nowhere", 404), ("/stations/Broken", 500)]:
before = requests_to(path)
with patch("time.sleep"), pytest.raises(HTTPError):
get_with_retries(f"{BASE}{path}", key)
assert requests_to(path) == before + 1, f"Don't try a {status} again."
with patch(f"{__name__}.get_json", side_effect=[URLError("refused"), TimeoutError("slow"), {}]):
with patch("time.sleep"):
assert get_with_retries("http://example.invalid/", key) == {}, (
"Try again after a URLError and a TimeoutError."
)
before = requests_to("/stations")
try:
with patch("time.sleep"):
get_with_retries(f"{BASE}/stations?delay=0.5", key, attempts=2, timeout=0.1)
except TimeoutError:
pass
else:
raise AssertionError("A 0.5 s delay with timeout=0.1 should time out: pass timeout on.")
assert requests_to("/stations") == before + 2, "Try again after a timeout."
print("passed")7. Testing without the service¶
describe_station turns your fetch_station’s answers into a sentence for a person:
def describe_station(base_url, name, key):
"""Return a sentence about a station's rainfall, or about what went wrong."""
try:
data = fetch_station(base_url, name, key)
except (URLError, TimeoutError):
return "The weather service didn't answer; try again later."
if data is None:
return f"There is no station named {name}."
total = round(sum(reading["rain_mm"] for reading in data["readings"]), 1)
return f"{name} had {total} mm of rain."
print(describe_station(BASE, "Hilltop", key))
print(describe_station(BASE, "Nowhere", key))Exercise L17.7 (LO-17.3, ★★, about 15 minutes)¶
Write
api_key(), which returns the value of the environment variableLAB17_KEY, and raisesRuntimeErrorwith a message that names the variable if it is missing or empty.Write two test functions, with names that start with
test_, that check whatdescribe_stationsays when the service can’t be reached: one in whichurlopenraisesURLError, and one in which it raisesTimeoutError. Usepatch. In a notebook, the names you define live in a module named__main__, soget_jsonlooks upurlopenas"__main__.urlopen".
The check runs your tests on describe_station, where they must pass, and on two broken
versions of it, where at least one must fail.
def api_key():
"""Return the API key from the environment variable LAB17_KEY."""
...assert api_key() == LAB_KEY, "Return the value of LAB17_KEY."
for value in ["", None]:
environment = {"LAB17_KEY": value} if value is not None else {}
with patch.dict(os.environ, environment, clear=value is None):
with pytest.raises(RuntimeError, match="LAB17_KEY"):
api_key()
assert api_key() == LAB_KEY, "patch.dict should have put the variable back."
your_tests = [value for name, value in list(globals().items())
if name.startswith("test_") and callable(value)]
assert len(your_tests) >= 2, f"Write at least two test functions, not {len(your_tests)}."
real_describe = describe_station
def catches_nothing(base_url, name, key):
data = fetch_station(base_url, name, key)
if data is None:
return f"There is no station named {name}."
total = round(sum(reading["rain_mm"] for reading in data["readings"]), 1)
return f"{name} had {total} mm of rain."
def catches_only_urlerror(base_url, name, key):
try:
return catches_nothing(base_url, name, key)
except URLError:
return "The weather service didn't answer; try again later."
try:
for test in your_tests:
test()
for broken in [catches_nothing, catches_only_urlerror]:
globals()["describe_station"] = broken
failures = 0
for test in your_tests:
try:
test()
except Exception:
failures += 1
assert failures, f"No test fails when describe_station is {broken.__name__}."
finally:
globals()["describe_station"] = real_describe
print("passed")Summary¶
A
with connection:block saved all of its changes or none: the stock that failed its check took the update before it down too.Constraints in
CREATE TABLE, includingUNIQUE, made the database refuse bad readings on its own, whichever program sent them.GROUP BYwithSUMlet the database add up each station’s rain, androwcounttoldcorrect_readingwhether anything matched.An f-string let a station name rewrite the query; a placeholder made the same name harmless.
get_jsonandfetch_stationhandled each HTTP status as it deserves, andget_with_retriestried again only after errors that can go away, waiting longer each time.patchstood in for a service that was down or slow, so the tests could check what a person sees in those cases without waiting for them to happen.