Final project: a price tracker command-line tool
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
The idea
For the final project we build pricewatch, a small command-line tool. You give it a list of products and the URLs of JSON endpoints that return their price. It fetches all of them concurrently, stores each price in an SQLite database, and tells you what changed since the last run. It is small enough to finish in an evening and uses ideas from the whole course: dataclasses, type hints, async code, context managers, a package layout and tests.
The endpoints are your own. For testing we will use fake ones, so you do not depend on any real shop. Real shops often forbid automated scraping, so check the terms before pointing a tool like this at someone's website.
Project layout
pricewatch/
pyproject.toml
src/pricewatch/
__init__.py
models.py
fetch.py
store.py
cli.py
tests/
test_store.py
test_fetch.py
Set up pyproject.toml as in the packaging lesson, with httpx as a dependency and pytest and pytest-asyncio as dev dependencies, plus a script entry pricewatch = "pricewatch.cli:main".
The model
# models.py
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Product:
name: str
url: str
@dataclass(frozen=True, slots=True)
class PriceReading:
product: str
price: float
fetched_at: str # ISO timestamp
Storage with a context manager
# store.py
import sqlite3
from contextlib import closing
from datetime import datetime, timezone
from pricewatch.models import PriceReading
class PriceStore:
def __init__(self, path: str) -> None:
self.path = path
with closing(sqlite3.connect(self.path)) as conn, conn:
conn.execute(
"CREATE TABLE IF NOT EXISTS prices ("
"product TEXT NOT NULL, price REAL NOT NULL, fetched_at TEXT NOT NULL)"
)
def last_price(self, product: str) -> float | None:
with closing(sqlite3.connect(self.path)) as conn:
row = conn.execute(
"SELECT price FROM prices WHERE product = ? "
"ORDER BY rowid DESC LIMIT 1",
(product,),
).fetchone()
return None if row is None else float(row[0])
def add(self, reading: PriceReading) -> None:
with closing(sqlite3.connect(self.path)) as conn, conn:
conn.execute(
"INSERT INTO prices VALUES (?, ?, ?)",
(reading.product, reading.price, reading.fetched_at),
)
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
The pattern with closing(conn) as conn, conn: is worth understanding. closing makes sure the connection is closed at the end. Using the connection itself as a context manager commits on success and rolls back on an error. The question marks are parameters. Never put values into SQL with f-strings, because that is how SQL injection happens.
Fetching concurrently
# fetch.py
import asyncio
import httpx
from pricewatch.models import PriceReading, Product
from pricewatch.store import now_iso
async def fetch_price(client: httpx.AsyncClient, product: Product) -> PriceReading:
response = await client.get(product.url)
response.raise_for_status()
price = float(response.json()["price"])
return PriceReading(product.name, price, now_iso())
async def fetch_all(products: list[Product], limit: int = 5):
gate = asyncio.Semaphore(limit)
async with httpx.AsyncClient(timeout=10) as client:
async def one(p: Product):
async with gate:
try:
return await fetch_price(client, p)
except (httpx.HTTPError, KeyError, ValueError) as error:
return error
return await asyncio.gather(*(one(p) for p in products))
Each fetch catches its own errors and returns them as values, so one broken product does not kill the others. The semaphore keeps us polite to servers. The caller then sorts the results into readings and errors.
The command line
# cli.py
import argparse
import asyncio
import json
from pathlib import Path
from pricewatch.fetch import fetch_all
from pricewatch.models import PriceReading, Product
from pricewatch.store import PriceStore
def main() -> None:
parser = argparse.ArgumentParser(prog="pricewatch")
parser.add_argument("products_file", help="JSON file: [{name, url}, ...]")
parser.add_argument("--db", default="prices.db")
args = parser.parse_args()
data = json.loads(Path(args.products_file).read_text(encoding="utf-8"))
products = [Product(**item) for item in data]
store = PriceStore(args.db)
results = asyncio.run(fetch_all(products))
for product, result in zip(products, results):
if isinstance(result, Exception):
print(f"{product.name}: FAILED ({result})")
continue
reading: PriceReading = result
previous = store.last_price(product.name)
store.add(reading)
if previous is None:
print(f"{product.name}: {reading.price:.2f} (first reading)")
elif reading.price != previous:
print(f"{product.name}: {previous:.2f} -> {reading.price:.2f}")
else:
print(f"{product.name}: {reading.price:.2f} (no change)")
if __name__ == "__main__":
main()
Tests
# tests/test_store.py
from pricewatch.models import PriceReading
from pricewatch.store import PriceStore
def test_last_price_is_none_for_new_product(tmp_path):
store = PriceStore(str(tmp_path / "t.db"))
assert store.last_price("tea") is None
def test_last_price_returns_most_recent(tmp_path):
store = PriceStore(str(tmp_path / "t.db"))
store.add(PriceReading("tea", 120.0, "2025-01-01T00:00:00+00:00"))
store.add(PriceReading("tea", 130.0, "2025-01-02T00:00:00+00:00"))
assert store.last_price("tea") == 130.0
To test fetching without a network, httpx has a MockTransport that returns canned responses. Pass it to the client and assert on the result.
What to do next
- Add type checking with
mypy --strictand fix what it finds. The mixed result list infetch_allis a good place to improve the types. - Add a
historycommand that prints every price for one product. - Write the tests for
fetch.pywithhttpx.MockTransport, including a failing endpoint. - Profile a run with a hundred products and see where time goes. Is it the network or the database?
What this project teaches
None of the pieces is complicated alone. The skill is in how they fit: a small data model, storage separated from fetching, I/O done concurrently, errors treated as data, and tests around the parts that can break. When you can build and explain something like this, you are working at an intermediate to advanced level.
Try it yourself
Create a products.json with three entries that point to a tiny local server (python -m http.server can serve static JSON files with a price key). Run pricewatch, edit one of the JSON files, and run it again to see the change reported.
# store.py
import sqlite3
from contextlib import closing
from datetime import datetime, timezone
from pricewatch.models import PriceReading
class PriceStore:
def __init__(self, path: str) -> None:
self.path = path
with closing(sqlite3.connect(self.path)) as conn, conn:
conn.execute(
"CREATE TABLE IF NOT EXISTS prices ("
"product TEXT NOT NULL, price REAL NOT NULL, fetched_at TEXT NOT NULL)"
)
def last_price(self, product: str) -> float | None:
with closing(sqlite3.connect(self.path)) as conn:
row = conn.execute(
"SELECT price FROM prices WHERE product = ? "
"ORDER BY rowid DESC LIMIT 1",
(product,),
).fetchone()
return None if row is None else float(row[0])
def add(self, reading: PriceReading) -> None:
with closing(sqlite3.connect(self.path)) as conn, conn:
conn.execute(
"INSERT INTO prices VALUES (?, ?, ?)",
(reading.product, reading.price, reading.fetched_at),
)
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account