Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

These exercises practice what the Module 17 reading explained. They aren’t graded. Work in the folder m17 inside py101, where the reading’s books.py, make_books.py, weather_server.py, and weather_client.py are, and run tests with python -m pytest, using your environment’s Python, as in Module 13. Run python make_books.py first, so books.db holds its five books. Write your answer or your prediction first, then run the code to check it. The answers are in the collapsed blocks; open one only after you have an answer of your own.

Worked example: sorting by a column the user picks

A program that lists books should let its user choose the order: by title, by author, or by year. The column’s name has to go into the SQL itself, after ORDER BY, and the reading showed that a placeholder can’t hold a name: ORDER BY ? would sort by a constant string, which leaves the rows in no promised order. So the name must be put into the query as text, which is exactly what made unsafe.py dangerous.

The way out is to never put the user’s text in the query. The program checks it against a fixed set of names that the program itself chose, and puts in only one of those. Add this to books.py:

SORTABLE = {"title", "author", "year"}


def books_sorted(connection, column, descending=False):
    """Return (title, author, year) for every book, sorted by column."""
    if column not in SORTABLE:
        raise ValueError(f"can't sort by {column!r}; choose one of {sorted(SORTABLE)}")
    direction = "DESC" if descending else "ASC"
    query = f"SELECT title, author, year FROM books ORDER BY {column} {direction}, id"
    return connection.execute(query).fetchall()

This f-string is safe, and it’s worth seeing why. column reaches the f-string only after the check, so it is one of three strings written in the program, and direction is one of two. No character of the caller’s text can get into the query unless the program wrote the same text itself. The , id at the end breaks ties: two books by the same author come out in the order they were added, every time.

A short script, sort_books.py, uses it:

import sqlite3
import sys

from books import books_sorted

connection = sqlite3.connect("books.db")
try:
    rows = books_sorted(connection, sys.argv[1], descending="--desc" in sys.argv)
except ValueError as error:
    sys.exit(f"error: {error}")
finally:
    connection.close()
for title, author, year in rows:
    print(f"{year}  {author:<18} {title}")
python sort_books.py author --desc
python sort_books.py "year; DROP TABLE books"
1968  Ursula K. Le Guin  A Wizard of Earthsea
1969  Ursula K. Le Guin  The Left Hand of Darkness
1818  Mary Shelley       Frankenstein
1979  Douglas Adams      The Hitchhiker's Guide to the Galaxy
1958  Chinua Achebe      Things Fall Apart
error: can't sort by 'year; DROP TABLE books'; choose one of ['author', 'title', 'year']

The finally closes the connection whether the sort worked or raised. The tests check both directions and three refusals: an attack, a real column that isn’t on the list, and a name in the wrong case. Save them as test_sorting.py:

import sqlite3

import pytest

from books import books_sorted, create_table


@pytest.fixture
def connection():
    connection = sqlite3.connect(":memory:")
    create_table(connection)
    connection.executemany(
        "INSERT INTO books (title, author, year) VALUES (?, ?, ?)",
        [("Kindred", "Octavia E. Butler", 1979), ("Beloved", "Toni Morrison", 1987),
         ("Dune", "Frank Herbert", 1965)],
    )
    yield connection
    connection.close()


def test_sorted_by_year(connection):
    assert [year for _, _, year in books_sorted(connection, "year")] == [1965, 1979, 1987]


def test_sorted_by_title_descending(connection):
    titles = [title for title, _, _ in books_sorted(connection, "title", descending=True)]
    assert titles == ["Kindred", "Dune", "Beloved"]


@pytest.mark.parametrize("column", ["year; DROP TABLE books", "id", "Title"])
def test_refuses_other_columns(connection, column):
    with pytest.raises(ValueError, match="choose one of"):
        books_sorted(connection, column)

All five pass. _ is the usual name for a value that unpacking must take but the code doesn’t use.

Exercises

Exercise 17.1 (LO-17.1, ★, about 10 minutes)

Predict the five lines this program prints:

import sqlite3

connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE scores (name TEXT NOT NULL, points INTEGER NOT NULL)")
with connection:
    connection.executemany(
        "INSERT INTO scores VALUES (?, ?)", [("Ada", 3), ("Grace", 5), ("Ada", 4)]
    )
query = "SELECT name, SUM(points) FROM scores GROUP BY name ORDER BY name"
print(connection.execute(query).fetchall())
with connection:
    print(connection.execute("DELETE FROM scores WHERE points < ?", (4,)).rowcount)
print(connection.execute("SELECT COUNT(*) FROM scores").fetchone())
try:
    with connection:
        connection.execute("DELETE FROM scores")
        connection.execute("INSERT INTO scores VALUES (?, ?)", ("Alan", None))
except sqlite3.IntegrityError as error:
    print(error)
print(connection.execute("SELECT name FROM scores ORDER BY points").fetchall())
connection.close()
Answer
[('Ada', 7), ('Grace', 5)]
1
(2,)
NOT NULL constraint failed: scores.points
[('Ada',), ('Grace',)]

GROUP BY name adds Ada’s two scores together. The DELETE removes only Ada’s 3, so two rows remain, and fetchone returns the count as a one-item tuple. In the try, the DELETE without a WHERE removes every row, but the INSERT of None breaks NOT NULL, so the block rolls back the DELETE too, and both rows are still there, Ada’s 4 before Grace’s 5.

Exercise 17.2 (LO-17.1, ★★, about 15 minutes)

A shopping list keeps one row per item. Save this as shopping.py, and finish add_item: if the item is already on the list, it adds to the quantity there; otherwise it adds a new row. Do both in one transaction, so a refused quantity changes nothing.

"""A shopping list in a database."""


def create_table(connection):
    connection.execute("""
        CREATE TABLE items (
            name TEXT PRIMARY KEY,
            quantity INTEGER NOT NULL CHECK (quantity > 0)
        )
    """)


def add_item(connection, name, quantity):
    """Add quantity of name to the list, on top of any quantity already there."""
    with connection:
        cursor = connection.execute(
            "UPDATE items SET quantity = quantity + ? WHERE name = ?", (quantity, name)
        )
        # Your code here.

These tests, in test_shopping.py, should pass:

import sqlite3

import pytest

from shopping import add_item, create_table


@pytest.fixture
def connection():
    connection = sqlite3.connect(":memory:")
    create_table(connection)
    yield connection
    connection.close()


def items(connection):
    return connection.execute("SELECT name, quantity FROM items ORDER BY name").fetchall()


def test_new_item(connection):
    add_item(connection, "apples", 6)
    assert items(connection) == [("apples", 6)]


def test_item_already_there(connection):
    add_item(connection, "apples", 6)
    add_item(connection, "eggs", 12)
    add_item(connection, "apples", 4)
    assert items(connection) == [("apples", 10), ("eggs", 12)]


def test_refused_quantity_changes_nothing(connection):
    add_item(connection, "apples", 6)
    with pytest.raises(sqlite3.IntegrityError):
        add_item(connection, "pears", 0)
    with pytest.raises(sqlite3.IntegrityError):
        add_item(connection, "apples", -7)
    assert items(connection) == [("apples", 6)]
    assert not connection.in_transaction
Hint

The UPDATE changes nothing when the item isn’t on the list yet. Which attribute of cursor tells you that?

Answer
def add_item(connection, name, quantity):
    """Add quantity of name to the list, on top of any quantity already there."""
    with connection:
        cursor = connection.execute(
            "UPDATE items SET quantity = quantity + ? WHERE name = ?", (quantity, name)
        )
        if cursor.rowcount == 0:
            connection.execute(
                "INSERT INTO items (name, quantity) VALUES (?, ?)", (name, quantity)
            )

rowcount is 0 when no row has that name, so the function inserts one. Both statements are inside the with block, so when the CHECK refuses a quantity, nothing from the call is kept. Adding -7 to 6 apples would leave -1, which the CHECK refuses too, because it applies to the result of an UPDATE as well as to a new row.

SQLite can also do this in one statement, called an upsert, which it has supported since version 3.24.0 (2018):

connection.execute(
    "INSERT INTO items (name, quantity) VALUES (?, ?) "
    "ON CONFLICT (name) DO UPDATE SET quantity = quantity + excluded.quantity",
    (name, quantity),
)

ON CONFLICT (name) applies when the PRIMARY KEY refuses a second row with the same name, and excluded.quantity is the quantity the refused row would have had. It passes the same tests.

Exercise 17.3 (LO-17.1, ★★, about 15 minutes)

LIKE compares text with a pattern, in which % stands for any run of characters, so title LIKE '%the%' is true for every title that contains “the”. In SQLite, LIKE ignores the difference between capital and small letters, for the letters A to Z. This search function builds its query with an f-string:

def search_unsafe(connection, word):
    query = f"SELECT title FROM books WHERE title LIKE '%{word}%' ORDER BY title"
    return [title for (title,) in connection.execute(query)]
  1. What happens when a user searches for Hitchhiker's?

  2. A first attempt at a fix writes the query as "... WHERE title LIKE '%?%' ORDER BY title" and passes (word,). What happens, and why?

  3. Write search(connection, word) safely, and check it with the, Hitchhiker's, and %' OR '1'='1' --, where -- starts a comment in SQL.

Answer
  1. The apostrophe ends the string in the SQL, and the query fails with sqlite3.OperationalError: near "s": syntax error.

  2. It fails with sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied. A ? inside quotation marks is part of a string, the three characters %?%, not a placeholder, so the statement has no placeholders at all.

  3. The % signs go into the value, not the SQL:

    def search(connection, word):
        query = "SELECT title FROM books WHERE title LIKE ? ORDER BY title"
        return [title for (title,) in connection.execute(query, (f"%{word}%",))]

    search(connection, "the") returns ["The Hitchhiker's Guide to the Galaxy", 'The Left Hand of Darkness'], Hitchhiker's finds its one book, and the attack finds nothing. With search_unsafe, the attack returns all five titles, out of order, because -- turned the ORDER BY into a comment.

% and _ (any one character) still work as wildcards inside the value, so a search for _ returns every book. If your users need to search for those characters themselves, SQLite’s LIKE takes an ESCAPE clause; see its documentation.

Exercise 17.4 (LO-17.2, ★, about 10 minutes)

For each situation, say what get_json from the reading raises, and whether a program should try the request again later.

  1. A user types the name of a station that doesn’t exist.

  2. The API key has expired.

  3. The service answers 503 Service Unavailable.

  4. The laptop’s Wi-Fi is off.

  5. The server takes 30 seconds to answer, and the timeout is 5 seconds.

  6. The service answers 400 Bad Request, because the program sent a date as 11/02/2026 where the API wants 2026-11-02.

Answer
  1. HTTPError with code 404. Trying again gets the same answer; tell the user there is no such station.

  2. HTTPError with code 401. Trying again doesn’t help; tell the user to get a new key.

  3. HTTPError with code 503. Yes: the service is overloaded or down for maintenance, and should recover. Wait longer between each attempt, as Lab 17’s get_with_retries did.

  4. URLError, with the cause in its reason. Trying again a few times is reasonable, but the message should say that the service couldn’t be reached, so the user can check their connection.

  5. TimeoutError. One or two more attempts are reasonable; if every attempt times out, report it.

  6. HTTPError with code 400. Never: the request itself is wrong, and will be wrong every time. The bug is in the program, which should send the date in the API’s format.

The 4xx codes, except 429, say that the request has to change; the 5xx codes, 429, and the failures with no answer at all say that the same request might work later.

Exercise 17.5 (LO-17.2, ★★, about 20 minutes)

Write rain_report.py, which prints every station’s total rainfall, wettest first, using the functions in weather_client.py. It asks the API for the list of stations, then for each one. A station that disappears between the two requests, so that station returns None, is left out. Its main gives the same error messages as weather_client.py’s. With the server running and the key set, it prints:

Hilltop     13.3 mm
Harbor       8.6 mm
Mill Lane    7.4 mm
Hint

get_json(f"{base_url}/stations", key)["stations"] is the list of names. Sort (name, total) pairs with a key that puts the largest total first, as in Module 7.

Answer
"""Print every station's total rainfall, wettest first."""
import sys
from urllib.error import HTTPError, URLError

from weather_client import BASE_URL, api_key, get_json, station, total_rain


def rain_report(key, base_url=BASE_URL):
    """Return (name, total rainfall) for every station, wettest first."""
    names = get_json(f"{base_url}/stations", key)["stations"]
    totals = []
    for name in names:
        data = station(name, key, base_url)
        if data is not None:
            totals.append((name, total_rain(data)))
    return sorted(totals, key=lambda pair: (-pair[1], pair[0]))


def main():
    try:
        report = rain_report(api_key())
    except RuntimeError as error:
        sys.exit(f"error: {error}")
    except HTTPError as error:
        sys.exit(f"error: the weather service answered {error.code} {error.reason}")
    except (URLError, TimeoutError):
        sys.exit("error: the weather service didn't answer; try again later")
    for name, total in report:
        print(f"{name:<10} {total:5.1f} mm")


if __name__ == "__main__":
    main()

rain_report reuses the reading’s functions instead of building URLs again; station quotes Mill Lane itself. The key (-total, name) sorts by total, largest first, and by name when two totals are equal. With the server stopped, main prints error: the weather service didn't answer; try again later and exits with status 1.

The program makes one request for the list and one for each station. For three stations that is fine; for thousands, look for an API request that returns them all at once, because each request costs a round trip, and many APIs limit how many you may make.

Exercise 17.6 (LO-17.3, ★★, about 20 minutes)

Write two tests, in test_main.py, for weather_client.main: one that checks its message when the service can’t be reached, and one that checks its message when PY101_WEATHER_KEY is empty. Neither test may depend on the server or on your terminal’s environment variables.

Hint

main reads the station’s name from sys.argv, which patch can replace with a list for the test. sys.exit("message") raises the exception SystemExit, and the message is in its code attribute, so pytest.raises(SystemExit) as caught catches it.

Answer
from unittest.mock import patch
from urllib.error import URLError

import pytest

import weather_client


def test_main_when_the_service_is_down():
    refused = URLError(ConnectionRefusedError(111, "Connection refused"))
    with patch("sys.argv", ["weather_client.py", "Harbor"]):
        with patch.dict("os.environ", {"PY101_WEATHER_KEY": "any-key"}):
            with patch("weather_client.urlopen", side_effect=refused):
                with pytest.raises(SystemExit) as caught:
                    weather_client.main()
    assert caught.value.code == "error: the weather service didn't answer; try again later"


def test_main_without_a_key():
    with patch("sys.argv", ["weather_client.py", "Harbor"]):
        with patch.dict("os.environ", {"PY101_WEATHER_KEY": ""}):
            with pytest.raises(SystemExit) as caught:
                weather_client.main()
    assert "PY101_WEATHER_KEY" in caught.value.code

The first test sets the key itself, with patch.dict, so it passes whether or not your terminal has the variable. Each patch undoes itself when its block ends, so the tests leave sys.argv and the environment as they found them.

A test of main for a missing station would need main to use the fixture’s server, but patching weather_client.BASE_URL doesn’t do it: station’s default, base_url=BASE_URL, was computed once, when its def ran, and keeps the old address. That is one more reason to keep main thin and to test the functions under it, which take the address as an argument.