Objectives: LO-17.1, LO-17.2, LO-17.3
Prerequisites: Module 11,
Module 12,
Module 13, and
Module 16
Time: about 5.5 hours: 2 for this reading, 2 for Lab 17, and 1.5 for the
practice
So far your programs have kept their data in files that they read whole and write whole (Module
11). This module adds two other places data can live. A database stores data that a program
can search and change a piece at a time, and keeps it safe if the program stops halfway through a
change. A web API (application programming interface) is a service on another computer that
answers a program’s requests with data, usually as JSON. Both come with Python’s standard library:
sqlite3 for the database, and urllib.request for the requests. The module ends with how to test
code that calls a web API without depending on the network.
Work in a new folder, m17, in your py101 folder, and save each example there. As in Module 13,
python in a command stands for your environment’s Python, run by its path.
Databases with SQLite¶
Tables, rows, and SQL¶
A relational database keeps data in tables. A table has named columns, each holding one kind of value, and rows, each one record. A table of books might look like this:
| id | title | author | year | read |
|---|---|---|---|---|
| 1 | Frankenstein | Mary Shelley | 1818 | 0 |
| 2 | Things Fall Apart | Chinua Achebe | 1958 | 0 |
You don’t loop over the rows yourself. You describe what you want in SQL (Structured Query Language), and the database finds it: “the titles of the books before 1960, oldest first”. The database can answer that without reading every row into your program, which matters once a table holds millions of rows.
SQLite is a database that keeps a whole database in one ordinary file, with no separate
server program to install or run. Python’s sqlite3 module includes it, so it works wherever
Python does. Its developers list where it runs: every
Android and iOS device, and the Firefox, Chrome, and Safari web browsers, among others.
Creating a database¶
Save this as books.py. It holds the functions this section builds up, starting with one that
creates the table:
"""Functions for a database of books."""
def create_table(connection):
"""Create the books table."""
connection.execute("""
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER NOT NULL,
read INTEGER NOT NULL DEFAULT 0 CHECK (read IN (0, 1))
)
""")connection.execute runs one SQL statement. SQL keywords are written in capitals by custom, to
set them apart from names; SQL itself ignores their case. Each line inside the parentheses defines
a column, with its name, its type, and its constraints, rules the database enforces on every
row:
INTEGER PRIMARY KEYmakesidthe row’s identifier. SQLite fills it in with the next number when a row is added without one.TEXTandINTEGERare the types. SQLite also hasREALfor floats.NOT NULLrefuses a row with no value in that column.NULLis SQL’s missing value, whichsqlite3turns intoNone.DEFAULT 0fills inreadwhen a new row leaves it out.CHECK (read IN (0, 1))refuses any other value. SQLite has no type for true and false, soreadholds 1 or 0.
Constraints protect an invariant, as the checks in Module 14’s __init__ did, but the database
enforces them on every program that changes the table, not only yours.
Now save this as make_books.py, which makes the database file and fills the table:
"""Make books.db, a database of five books, starting fresh each time."""
import sqlite3
from pathlib import Path
from books import create_table
Path("books.db").unlink(missing_ok=True)
connection = sqlite3.connect("books.db")
create_table(connection)
books = [
("Frankenstein", "Mary Shelley", 1818),
("Things Fall Apart", "Chinua Achebe", 1958),
("A Wizard of Earthsea", "Ursula K. Le Guin", 1968),
("The Left Hand of Darkness", "Ursula K. Le Guin", 1969),
("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979),
]
with connection:
connection.executemany("INSERT INTO books (title, author, year) VALUES (?, ?, ?)", books)
count = connection.execute("SELECT COUNT(*) FROM books").fetchone()[0]
print(f"books.db holds {count} books")
connection.close()books.db holds 5 booksPath("books.db").unlink(missing_ok=True)deletes the file if it exists, so every run starts from the same five books. Leave this line out of any program whose data you want to keep.sqlite3.connect("books.db")opens the database in that file, and creates the file if it doesn’t exist. It returns a connection, the object every later step goes through.connection.close()closes the database when the program is done with it.
The next two parts explain the rest: the question marks, and the with block.
Adding rows with placeholders¶
INSERT INTO books (title, author, year) VALUES (?, ?, ?) adds one row. Each ? is a
placeholder: the statement leaves a hole there, and sqlite3 fills it with the matching item
of a tuple you pass alongside. executemany runs the statement once for each tuple in the list.
Placeholders keep the values apart from the SQL. The database reads the statement first, with its holes, and receives each value separately, as data, never as SQL. A title such as “The Hitchhiker’s Guide to the Galaxy”, whose apostrophe would end a string in SQL, goes in safely. This matters more than it seems; “SQL injection” below shows why. Pass every value through a placeholder, every time.
Asking questions with SELECT¶
A SELECT statement asks for rows. Save this as query_books.py, and run it:
import sqlite3
connection = sqlite3.connect("books.db")
query = "SELECT title, year FROM books WHERE year < ? ORDER BY year"
for title, year in connection.execute(query, (1960,)):
print(year, title)
connection.close()1818 Frankenstein
1958 Things Fall ApartSELECT title, year names the columns to return, FROM books the table, WHERE year < ? the
condition each row must meet, and ORDER BY year the order; without ORDER BY, SQL promises no
order at all. execute returns a cursor, an iterator over the matching rows, each a tuple of
the columns you asked for. A cursor also has fetchone(), which returns the next row or None,
and fetchall(), which returns a list of the rest.
The values always go in a tuple, even when there is one: (1960,), with its comma. Without the
comma, (1960) is the number 1960, and execute raises sqlite3.ProgrammingError: parameters are of unsupported type. A string in place of the tuple is worse: sqlite3 treats it as a sequence of
characters, so "Achebe" is six values, and the error says Incorrect number of bindings supplied. The current statement uses 1, and there are 6 supplied.
SQL can also count and group. Add this to the end of query_books.py, before
connection.close():
query = "SELECT author, COUNT(*) FROM books GROUP BY author ORDER BY COUNT(*) DESC, author"
for author, count in connection.execute(query):
print(count, author)2 Ursula K. Le Guin
1 Chinua Achebe
1 Douglas Adams
1 Mary ShelleyGROUP BY author makes one result row for each author, and COUNT(*) counts the rows in each
group. ORDER BY COUNT(*) DESC, author sorts by the count, most first (DESC means descending),
then by name, as the key (-count, name) did in Module 7.
Tuples make you remember the order of the columns. Set the connection’s row_factory to
sqlite3.Row, and each row can be read by column name as well:
connection.row_factory = sqlite3.Row
book = connection.execute("SELECT * FROM books WHERE id = ?", (5,)).fetchone()
print(book["title"], book["year"])
print(dict(book))The Hitchhiker's Guide to the Galaxy 1979
{'id': 5, 'title': "The Hitchhiker's Guide to the Galaxy", 'author': 'Douglas Adams', 'year': 1979, 'read': 0}SELECT * returns every column. dict(book) turns a row into a dictionary, which is handy for
turning query results into JSON (Module 11).
Changing rows with UPDATE¶
UPDATE changes the rows that meet a condition. Save this as mark_read.py, which takes an
author’s name from the command line (Module 9):
import sqlite3
import sys
connection = sqlite3.connect("books.db")
with connection:
cursor = connection.execute("UPDATE books SET read = 1 WHERE author = ?", (sys.argv[1],))
print(f"marked {cursor.rowcount} books as read")
connection.close()python mark_read.py "Ursula K. Le Guin"
python mark_read.py "Ursula Le Guin"marked 2 books as read
marked 0 books as readThe cursor’s rowcount is the number of rows the statement changed. An UPDATE that matches no
rows isn’t an error, so check rowcount when a change was supposed to happen: the second command
misspelled the name and changed nothing. DELETE FROM books WHERE id = ? removes rows the same
way, and rowcount says how many. An UPDATE or DELETE without a WHERE changes every row in
the table.
Transactions: all or nothing¶
A change to a database isn’t saved when execute runs. It becomes part of a transaction, a
group of changes that the database saves together, when the program commits them, or
discards together, when it rolls them back. A connection used in a with statement does this
for you: when the block ends normally, it commits; when the block raises an exception, it rolls
back every change made in the block, and the exception continues.
All or nothing is what a program needs when one change has several steps. Save this as
rollback.py. Its second update breaks the CHECK constraint:
import sqlite3
connection = sqlite3.connect("books.db")
try:
with connection:
connection.execute("UPDATE books SET read = 1 WHERE title = ?", ("Frankenstein",))
connection.execute("UPDATE books SET read = 2 WHERE title = ?", ("Things Fall Apart",))
except sqlite3.IntegrityError as error:
print("not saved:", error)
for (title,) in connection.execute("SELECT title FROM books WHERE read = 1"):
print("read:", title)
connection.close()not saved: CHECK constraint failed: read IN (0, 1)
read: A Wizard of Earthsea
read: The Left Hand of DarknessThe first update worked, but the database rolled it back with the second, so Frankenstein isn’t
marked as read. for (title,) in ... unpacks each one-column row, as for title, year in ...
unpacked two.
The with statement manages the transaction, not the connection: unlike a file’s with, it
doesn’t close anything, so still call connection.close(). And without a commit, changes are
lost. A program that runs an INSERT and closes the connection, with no with block and no
connection.commit(), sees its new row until it closes, and the row is gone the next time any
program opens the file.
SQL injection¶
Placeholders can look like extra work when string formatting seems to do the same job. Save this
as unsafe.py. It is the most common security mistake in programs that use a database, so don’t
copy it into your own code:
import sqlite3
import sys
def titles_by(connection, author):
"""Return the titles of an author's books. Unsafe: don't copy this."""
query = f"SELECT title FROM books WHERE author = '{author}'"
return [title for (title,) in connection.execute(query)]
connection = sqlite3.connect("books.db")
print(titles_by(connection, sys.argv[1]))
connection.close()Run make_books.py again to start fresh, then try three names:
python make_books.py
python unsafe.py "Douglas Adams"
python unsafe.py "nobody' OR '1'='1"
python unsafe.py "Patrick O'Brian"books.db holds 5 books
["The Hitchhiker's Guide to the Galaxy"]
['Frankenstein', 'Things Fall Apart', 'A Wizard of Earthsea', 'The Left Hand of Darkness', "The Hitchhiker's Guide to the Galaxy"]
sqlite3.OperationalError: near "Brian": syntax errorThe first name works. The second returns every book in the table, because the f-string pastes the name into the SQL, and the name’s quotation marks change the statement:
SELECT title FROM books WHERE author = 'nobody' OR '1'='1''1'='1' is true for every row, so the condition matches them all. This is SQL injection:
input that is meant to be a value becomes part of the statement. In a real program, the same trick
can read other people’s data, log in without a password, or change and delete rows. The third name
shows the same flaw from the other side: an honest name with an apostrophe breaks the query.
sqlite3 refuses to run two statements in one execute (You can only execute one statement at a time.), which blocks the attack that adds ; DROP TABLE books to delete the table. That is no
defense: the attack above needs only one statement, and other databases and their Python
libraries don’t all refuse.
The fix is a placeholder. Add this function to books.py:
def titles_by(connection, author):
"""Return the titles of an author's books, in the order they were added."""
query = "SELECT title FROM books WHERE author = ? ORDER BY id"
return [title for (title,) in connection.execute(query, (author,))]With it, "nobody' OR '1'='1" is one strange name with no books, and "Patrick O'Brian" is a
name with an apostrophe: both return [], because the database never reads either as SQL.
Placeholders work only for values, not for the names of tables or columns: SELECT ? FROM books
with ("title",) returns the string 'title' for every row. When a program must choose a column
from input, such as a sort order the user picks, check the input against a fixed set of allowed
names in your code, and refuse anything else.
Testing database code¶
Tests of database code need a database, and each test should start from a fresh one, as each test
in Module 13 got a fresh folder from tmp_path. sqlite3.connect(":memory:") makes a database
that lives in memory only and disappears when its connection closes, which makes it quick and
leaves no files behind.
A fixture can do work after its test, too. If it uses yield instead of return, pytest runs it
up to the yield, hands the yielded value to the test, and runs the rest after the test ends,
whether the test passed or failed. That is the same shape as Module 16’s context managers. Save
this as test_books.py:
import sqlite3
import pytest
from books import create_table, titles_by
@pytest.fixture
def connection():
"""A database in memory with an empty books table, closed after the test."""
connection = sqlite3.connect(":memory:")
create_table(connection)
yield connection
connection.close()
def add(connection, title, author, year):
connection.execute(
"INSERT INTO books (title, author, year) VALUES (?, ?, ?)", (title, author, year)
)
def test_titles_by(connection):
add(connection, "Kindred", "Octavia E. Butler", 1979)
add(connection, "Parable of the Sower", "Octavia E. Butler", 1993)
add(connection, "Beloved", "Toni Morrison", 1987)
assert titles_by(connection, "Octavia E. Butler") == ["Kindred", "Parable of the Sower"]
def test_titles_by_an_author_with_an_apostrophe(connection):
add(connection, "Master and Commander", "Patrick O'Brian", 1969)
assert titles_by(connection, "Patrick O'Brian") == ["Master and Commander"]
def test_titles_by_is_not_fooled_by_injection(connection):
add(connection, "Kindred", "Octavia E. Butler", 1979)
assert titles_by(connection, "nobody' OR '1'='1") == []
def test_read_must_be_0_or_1(connection):
with pytest.raises(sqlite3.IntegrityError):
connection.execute(
"INSERT INTO books (title, author, year, read) VALUES ('Kindred', 'Butler', 1979, 2)"
)add is a helper, not a test: its name doesn’t start with test, so pytest doesn’t run it on its
own. The tests never commit, because each connection is thrown away at the end of its test. The
last test checks the table’s own constraint, with a statement that has no values from outside, so
it needs no placeholders. Running python -m pytest test_books.py passes all four.
Web APIs¶
Requests and responses¶
When a program fetches data from a web API, it uses HTTP (Hypertext Transfer Protocol), the same protocol a browser uses to fetch a page. The program sends a request, and the server sends back a response:
The request names a method, such as
GETto read data orPOSTto send it, and a URL, such ashttp://127.0.0.1:8017/stations/Harbor. The URL’s path (/stations/Harbor) says which data, and an optional query string after a?(?delay=1) adds settings.Both carry headers, named values about the message. A request’s
Accept: application/jsonasks for JSON; an API often wants a key in a header too.The response starts with a status code, a three-digit number that says how the request went, and then a body, the data itself, here JSON.
The status code’s first digit gives its class:
| Codes | Meaning | Common ones |
|---|---|---|
| 2xx | Success | 200 OK |
| 4xx | A problem with the request: the client’s to fix | 400 Bad Request, 401 Unauthorized (no key or a wrong one), 404 Not Found, 429 Too Many Requests |
| 5xx | A problem on the server: the request might work later | 500 Internal Server Error, 503 Service Unavailable |
The difference decides what a program should do. Repeating a request that got a 404 gets another 404, but a request that got a 503, or got no answer at all, might work a minute later.
A weather API on your own computer¶
Real APIs need an account, change without notice, limit how often you may call them, and stop
working when your network does. To learn without those problems, run one on your own computer.
Save this as weather_server.py. You don’t need to follow every line: its job is to answer, and
this module’s subject is the program that asks.
"""A small weather API for Module 17. It answers only on this computer."""
import json
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, unquote, urlsplit
DEMO_KEY = "py101-demo-key"
STATIONS = {
"Harbor": {"elevation_m": 4, "readings": [
{"day": "2026-11-02", "temp_c": 8.5, "rain_mm": 1.2},
{"day": "2026-11-03", "temp_c": 11.0, "rain_mm": 0.0},
{"day": "2026-11-04", "temp_c": 6.5, "rain_mm": 7.4},
]},
"Hilltop": {"elevation_m": 212, "readings": [
{"day": "2026-11-02", "temp_c": 4.0, "rain_mm": 3.1},
{"day": "2026-11-03", "temp_c": 6.5, "rain_mm": 0.4},
{"day": "2026-11-04", "temp_c": 2.5, "rain_mm": 9.8},
]},
"Mill Lane": {"elevation_m": 38, "readings": [
{"day": "2026-11-02", "temp_c": 7.0, "rain_mm": 0.8},
{"day": "2026-11-03", "temp_c": 9.5, "rain_mm": 0.0},
{"day": "2026-11-04", "temp_c": 5.5, "rain_mm": 6.6},
]},
}
class WeatherHandler(BaseHTTPRequestHandler):
"""Answer GET requests for /stations and /stations/<name>."""
def do_GET(self):
url = urlsplit(self.path)
delay = float(parse_qs(url.query).get("delay", ["0"])[0])
time.sleep(delay)
parts = [unquote(part) for part in url.path.strip("/").split("/")]
if self.headers.get("X-API-Key") != DEMO_KEY:
self.send_json(401, {"error": "missing or wrong API key"})
elif parts == ["stations"]:
self.send_json(200, {"stations": sorted(STATIONS)})
elif len(parts) == 2 and parts[0] == "stations" and parts[1] in STATIONS:
self.send_json(200, {"name": parts[1], **STATIONS[parts[1]]})
else:
self.send_json(404, {"error": f"nothing at {url.path}"})
def send_json(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 # The client stopped waiting, as a client with a short timeout does.
def make_server(port=8017):
"""Return a server for the weather API on this computer; port 0 picks a free port."""
return ThreadingHTTPServer(("127.0.0.1", port), WeatherHandler)
if __name__ == "__main__":
server = make_server(int(sys.argv[1]) if len(sys.argv) > 1 else 8017)
print(f"Serving on http://127.0.0.1:{server.server_address[1]}. Press Ctrl+C to stop.")
try:
server.serve_forever()
except KeyboardInterrupt:
print("Stopped.")The server answers three kinds of request: /stations lists the stations, /stations/<name>
gives one station’s readings, and anything else gets a 404. It requires an API key, in a header
named X-API-Key, and a query string of ?delay=2 makes it wait 2 seconds before answering, so
you can see what a slow server does to your program.
127.0.0.1 is the address every computer uses for itself, so only programs on your computer can
reach this server. A port is a number that picks one program among those listening on an
address; this one listens on 8017. Python’s documentation warns that http.server is not meant
for real services, because it implements only basic security checks; it is fine for a test like
this one.
Open a second terminal (Terminal > New Terminal in VS Code), go to m17, and start the
server there:
python weather_server.pyServing on http://127.0.0.1:8017. Press Ctrl+C to stop.Leave it running. Open http://127.0.0.1:8017/stations in your web browser. The browser sends no
key, so it shows {"error": "missing or wrong API key"}, and the server’s terminal prints a line
for the request, ending in 401.
Requesting JSON with urllib.request¶
Work in your first terminal from here on. Save this as weather_client.py. It starts with the
function that does the request, and grows through the rest of this section:
"""Print a station's rainfall from the Module 17 weather API."""
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
BASE_URL = "http://127.0.0.1:8017"
def get_json(url, key, timeout=5.0):
"""Return the JSON at url. Raise HTTPError, URLError, or TimeoutError if that fails."""
request = Request(url, headers={"Accept": "application/json", "X-API-Key": key})
with urlopen(request, timeout=timeout) as response:
return json.load(response)Requestholds the URL and the request’s headers.urlopensends the request and returns the response, which is a file-like object:withcloses it, andjson.loadreads the body and turns it into Python values, as it did with a file in Module 11.response.statusholds the status code.timeout=5.0stops waiting after 5 seconds. Without a timeout, a server that never answers makes your program wait forever. Always pass one.
To try it, start Python in the first terminal with python, and type:
from weather_client import get_json
get_json("http://127.0.0.1:8017/stations", "py101-demo-key"){'stations': ['Harbor', 'Hilltop', 'Mill Lane']}A URL can’t contain a space, so a station named Mill Lane must be written Mill%20Lane in the
path. quote from urllib.parse does this, and leaves letters and digits alone:
quote("Mill Lane") is 'Mill%20Lane'. Pasting the name in unquoted makes urlopen raise
http.client.InvalidURL.
When a request fails¶
A request can fail in three different ways, each with its own exception:
| What happened | What urlopen raises | str of the exception |
|---|---|---|
| The server answered with a 4xx or 5xx status | urllib.error.HTTPError, with the status in .code and its name in .reason | HTTP Error 404: Not Found |
| No answer: no server at that address, no network, or a name that doesn’t exist | urllib.error.URLError, with the cause in .reason | <urlopen error [Errno 111] Connection refused> on Linux |
| The server didn’t answer within the timeout | TimeoutError (or URLError, with a TimeoutError as its .reason, if the time ran out while connecting) | timed out |
HTTPError is a subclass of URLError, so an except URLError would catch both. When you need to
tell them apart, put except HTTPError first. An HTTPError also works as a response: an API
usually sends a JSON body that explains the error, and json.load(error) reads it.
Add this function to weather_client.py. A missing station is a normal answer, so it returns
None, as a dictionary’s get does; every other failure is left for the caller to decide about:
def station(name, key, base_url=BASE_URL):
"""Return a station's data, or None if the service has no station by that name."""
try:
return get_json(f"{base_url}/stations/{quote(name)}", key)
except HTTPError as error:
if error.code == 404:
return None
raisebase_url is a parameter, with the real address as its default, so a test can point the function
at another server.
Keeping API keys out of your code¶
A real API gives each user a secret API key, which identifies them on every request. Anyone who has your key can use the service as you: run up your bill, use up your limit, or get your account closed. A key written in your code ends up in Git, and pushing to GitHub publishes it. Deleting the line later doesn’t help, because the commit that added it is still in the history (Module 10). If a key ever reaches a repository, revoke it on the service’s website and get a new one.
Keep keys in environment variables instead: named values that a terminal passes to each program it starts. Set one in your first terminal. In PowerShell on Windows:
$env:PY101_WEATHER_KEY = "py101-demo-key"On macOS and Linux:
export PY101_WEATHER_KEY="py101-demo-key"The variable lasts until you close that terminal, and only programs started from it see it. A
program reads it from os.environ, a dictionary of the environment variables. Add this function
to weather_client.py:
def api_key():
"""Return the API key from the environment variable PY101_WEATHER_KEY."""
key = os.environ.get("PY101_WEATHER_KEY", "")
if not key:
raise RuntimeError("set the environment variable PY101_WEATHER_KEY to your API key")
return keyThe error message says how to fix the problem, because the person who sees it is usually setting
the program up for the first time. The demonstration server’s key sits in weather_server.py
because it guards nothing; a real service keeps its keys in a database, never in its code.
The whole client¶
Add the rest of weather_client.py:
def total_rain(data):
"""Return the total rainfall in a station's readings, in millimeters."""
return round(sum(reading["rain_mm"] for reading in data["readings"]), 1)
def main():
name = sys.argv[1]
try:
data = station(name, 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")
if data is None:
sys.exit(f"error: no station named {name!r}")
print(f"{data['name']}: {total_rain(data)} mm of rain")
if __name__ == "__main__":
main()main turns each exception into a message for a person, and leaves the functions above it to
raise, so other programs and tests can use them. sys.exit with a string prints the string and
ends the program with exit status 1 (Module 9). With the key set and the server running:
python weather_client.py Harbor
python weather_client.py "Mill Lane"
python weather_client.py NowhereHarbor: 8.6 mm of rain
Mill Lane: 7.4 mm of rain
error: no station named 'Nowhere'Now stop the server with Ctrl+C in its terminal, where it prints Stopped., and run
python weather_client.py Harbor again:
error: the weather service didn't answer; try again laterStart the server again before you go on.
Testing code that calls an API¶
Tests that call a real web API are slow, fail whenever the network or the service does, and may use up your limit or cost money. They also can’t make the service fail on demand, so they can’t check that your program handles a timeout. Three habits fix this.
Keep the processing apart from the request¶
total_rain takes the data, not a URL, so a test can pass it a dictionary, with no server at all:
def test_total_rain():
data = {"readings": [{"rain_mm": 0.1}, {"rain_mm": 0.2}]}
assert weather_client.total_rain(data) == 0.3The more of a program’s logic lives in functions like this one, the less of it needs the network
to be tested. Without the round, this test fails: 0.1 + 0.2 is 0.30000000000000004 (Module
2).
A local server in a fixture¶
To test the request itself, start a server inside the test run. Save this as
test_weather_client.py:
import threading
from unittest.mock import patch
from urllib.error import HTTPError, URLError
import pytest
import weather_client
from weather_server import DEMO_KEY, make_server
@pytest.fixture
def base_url():
"""Run the weather API on a free port for one test, and stop it afterwards."""
server = make_server(port=0)
thread = threading.Thread(target=server.serve_forever)
thread.start()
yield f"http://127.0.0.1:{server.server_address[1]}"
server.shutdown()
server.server_close()
thread.join()
def test_station(base_url):
data = weather_client.station("Mill Lane", DEMO_KEY, base_url)
assert data["elevation_m"] == 38
assert weather_client.total_rain(data) == 7.4
def test_no_such_station(base_url):
assert weather_client.station("Nowhere", DEMO_KEY, base_url) is None
def test_wrong_key(base_url):
with pytest.raises(HTTPError) as caught:
weather_client.station("Harbor", "not-the-key", base_url)
assert caught.value.code == 401
def test_slow_answer(base_url):
with pytest.raises(TimeoutError):
weather_client.get_json(f"{base_url}/stations?delay=1", DEMO_KEY, timeout=0.2)
def test_total_rain():
data = {"readings": [{"rain_mm": 0.1}, {"rain_mm": 0.2}]}
assert weather_client.total_rain(data) == 0.3make_server(port=0)asks the operating system for any free port, so the tests don’t clash with the server you left running on 8017.server.server_address[1]is the port it got.serve_foreverruns until the server is shut down, so it can’t run in the test’s own line of execution. A thread is a second line of execution in the same program, running at the same time.threading.Thread(target=server.serve_forever)makes one, andstart()sets it going, while the test goes on with its own work.After the
yield,shutdown()stopsserve_forever,server_close()releases the port, andjoin()waits for the thread to finish, so each test leaves nothing running.pytest.raises(...) as caughtkeeps the exception, so the test can check itscodeafterwards.test_slow_answerasks for a 1-second delay with a 0.2-second timeout. It checks that the timeout works, and takes 0.2 seconds, not 5.
Stand-ins with unittest.mock¶
A local server can’t easily stand in for every failure: a network that is down, for example.
unittest.mock, in the standard library, replaces a name with a mock, an object that records
how it is called and does whatever you configure it to: return a value, or raise an exception.
patch replaces the name for the length of a with block and puts the original back afterwards.
Add these two tests:
def test_service_down():
refused = URLError(ConnectionRefusedError(111, "Connection refused"))
with patch("weather_client.urlopen", side_effect=refused):
with pytest.raises(URLError):
weather_client.station("Harbor", DEMO_KEY)
def test_key_missing():
with patch.dict("os.environ", {"PY101_WEATHER_KEY": ""}):
with pytest.raises(RuntimeError, match="PY101_WEATHER_KEY"):
weather_client.api_key()patch("weather_client.urlopen", side_effect=refused)replacesurlopeninweather_clientwith a mock that raisesrefusedwhen called.side_effectwith an exception means “raise this”;return_value=...would mean “return this”.Patch the name where the code you test looks it up.
weather_clientdidfrom urllib.request import urlopen, which made a nameurlopeninweather_clientitself, and that is the nameget_jsonuses. Patching"urllib.request.urlopen"instead would change the name inurllib.requestand leaveweather_client’s alone, so the test would make a real request.patch.dictchanges a dictionary for the block, here the environment, and restores it, so the test can’t affect the variables of the tests after it.
Mocks have a cost: a test with a mock checks your code against what you believe the real thing does. If the belief is wrong, the test passes and the program fails. Use the real thing, or a local server, where you can, and mocks for what you can’t produce on demand.
Run every test in the folder:
python -m pytest============================= test session starts ==============================
platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/ada/py101/m17
plugins: nbmake-1.5.5, anyio-4.16.0, platformdirs-4.14.8
collected 11 items
test_books.py .... [ 36%]
test_weather_client.py ....... [100%]
============================== 11 passed in 2.06s ==============================Most of the 2 seconds go to stopping the servers: shutdown waits for serve_forever to notice,
which it checks for twice a second.
Common misconceptions¶
| Misconception | What’s true | An example that breaks it |
|---|---|---|
with connection: closes the database | It commits or rolls back the transaction, and leaves the connection open | After the with block in rollback.py, the SELECT still runs |
A change is saved when execute runs | It is saved when the transaction commits | An INSERT with no with block and no commit() is gone once the connection closes |
| An f-string is fine for values from my own program | Values come from users, files, and other programs, and any of them can contain SQL | unsafe.py returns every book for nobody' OR '1'='1, and crashes on O'Brian |
urlopen returns a response whatever the status | It raises HTTPError for a 4xx or 5xx status | get_json for /stations/Nowhere raises HTTP Error 404: Not Found |
patch replaces a function everywhere | It replaces one name in one module | Patching "urllib.request.urlopen" doesn’t change weather_client.urlopen |
| Deleting a committed API key makes it secret again | The commit that added it stays in the history | git log -p still shows the line, on every clone of the repository |
Summary¶
SQLite keeps a database in one file, and
sqlite3comes with Python.CREATE TABLEdefines columns with types and constraints;INSERT,SELECT,UPDATE, andDELETEadd, read, change, and remove rows.executereturns a cursor, androwcountsays how many rows changed.A
with connection:block is a transaction: it commits when the block ends and rolls back every change in it when the block raises. It doesn’t close the connection.Pass every value through a
?placeholder, in a tuple. Building SQL with string formatting allows SQL injection, where input becomes part of the statement.A web API answers HTTP requests.
urlopenwith aRequest, headers, and a timeout returns a response thatjson.loadreads. It raisesHTTPErrorfor a 4xx or 5xx status,URLErrorwhen there is no answer, andTimeoutErrorwhen the answer is too slow.Keep API keys in environment variables, read with
os.environ, and never in code.Test API code without the network: keep processing in functions that take data, run a local server in a fixture, and use
unittest.mock.patchfor failures you can’t produce, patching the name where your code looks it up.
Self-check¶
A table
readingshas the columnsstation,day, andrain_mm. Write the call that returns the total rainfall at the station whose name is in the variablename, as one number.Answer
connection.execute( "SELECT SUM(rain_mm) FROM readings WHERE station = ?", (name,) ).fetchone()[0]SUMadds a column over the matching rows, asCOUNT(*)counts them. The value goes through a placeholder, in a tuple of one item.fetchone()returns the one result row, and[0]its only column. With no matching rows,SUMreturnsNULL, which arrives asNone.What does this print, if
books.dbholds the five books frommake_books.py?connection = sqlite3.connect("books.db") with connection: connection.execute("UPDATE books SET year = 1959 WHERE id = ?", (2,)) connection.execute("UPDATE books SET author = NULL WHERE id = ?", (3,))Answer
It prints nothing and stops with
sqlite3.IntegrityError: NOT NULL constraint failed: books.author. The second update breaks theNOT NULLconstraint, and thewithblock rolls back both updates, so book 2’s year is still 1958.A colleague’s function removes every apostrophe from
namewithname.replace("'", ""), and then builds its query with an f-string. They say this makes it safe. What is wrong with the approach, even if no attack gets through?Answer
It changes the data: no user named O’Brian can ever be found, because the query looks for “OBrian”. And it depends on knowing every character that is special in SQL, which differs between databases; one forgotten case is an injection. A placeholder sends the value apart from the SQL, so the name stays as it is and nothing in it is read as SQL.
A program calls
get_jsonwith a URL whose server has crashed, and nothing at that address answers. Which exception does it get, and what should a command-line program do?Answer
URLError, with aConnectionRefusedErroras itsreason, because no connection could be made. A command-line program should print a short message that says the service didn’t answer and suggests trying again later, and exit with a nonzero status, asmaindoes. A traceback would tell the user nothing they can act on.weather_client.pybegan withimport urllib.requestand calledurllib.request.urlopen(...)inget_json. Which name should a test patch to makeget_jsonraise, and why?Answer
"urllib.request.urlopen". Nowget_jsonlooksurlopenup in theurllib.requestmodule each time it runs, so that is the name to replace. The rule is the same as before: patch the name where the code looks it up.
Further reading¶
The
sqlite3documentation for Python 3.12: its tutorial, and the how-to guides on placeholders and the connection as a context manager. The reference for everything this module did with databases.The SQLite documentation’s Query Language Understood by SQLite. Every SQL statement SQLite accepts, for when you need more than this module’s five.
OWASP’s SQL Injection Prevention Cheat Sheet. How injection attacks work, and the defenses in order of preference, from a group that studies web security.
MDN’s Overview of HTTP and its list of HTTP response status codes. A clear introduction to the protocol, and what each status code means.
HOWTO Fetch Internet Resources Using The urllib Package, from the Python documentation, with the
urllib.requestreference. More on requests, headers, and errors.unittest.mock, especially its section Where to patch, and the guide unittest.mock — getting started. What else a mock can do, and the rule this module’s last misconception comes from.pytest’s section on yield fixtures. Fixtures that clean up after their tests, in more detail.