Data Pipelines with Python — Data Engineering

Bookshop's Python pipeline is one pipeline.py: extract with parameterised SQL (?) against the app's database for one date, transform with pandas (drop…

Tonight the load for 1 October fails halfway, and whoever is on duty runs it once more. The next morning sales still holds 2 rows for that date, not 4, and the log says what happened. That's what you build in this lesson: a data pipeline in Python, one script that runs extract, transform and load for one date, records what happened, and is safe to run again. It's like the shop's cash book, filled in every night by whoever is on the late shift. The method is written on a sheet taped to the wall: take that day's receipts, throw out the doubled ones, write the total on that date's page. If it turns out wrong, that date's page is erased and written again, not added to underneath. The sheet on the wall is the script; the page per date is a partition in the warehouse.

The pipeline's shape

Step Function in pipeline.py At Bookshop
Extract extract(order_date) SQL against the app's database, one day of orders
Transform transform(df) pandas: drop doubled lines, empty cities, catalogue price, week
Load load(df, order_date) the sales table in the DuckDB warehouse warehouse.duckdb

Bookshop's app database is MySQL. So that it runs on a laptop with no server, the source here is a SQLite file, shop.db, holding exactly the same tables. In production you only change how you connect (through PyMySQL or SQLAlchemy, say); the query stays. The libraries come from pip install pandas duckdb (pandas 3.0.6, DuckDB 1.5.6). The script is one file, covered part by part.

Config from the environment

import argparse
import logging
import os
import sqlite3
import time
from datetime import date, timedelta

import duckdb
import pandas as pd

# Configuration from environment variables, not written in the code
SOURCE_DB = os.environ.get("SOURCE_DB", "shop.db")
WAREHOUSE_DB = os.environ.get("WAREHOUSE_DB", "warehouse.duckdb")
ATTEMPTS = int(os.environ.get("ATTEMPTS", "3"))

log = logging.getLogger("pipeline")

Extract with retries

EXTRACT_SQL = """
SELECT oi.id AS item_id, oi.order_id, oi.book_id, o.created_at,
       c.city, b.title, oi.qty, oi.price AS paid_price, b.price AS catalog_price
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN customers c ON c.id = o.customer_id
JOIN books b ON b.id = oi.book_id
WHERE o.created_at >= ? AND o.created_at < ?
"""


def extract(order_date: date) -> pd.DataFrame:
    tomorrow = order_date + timedelta(days=1)
    for attempt in range(1, ATTEMPTS + 1):
        try:
            con = sqlite3.connect(f"file:{SOURCE_DB}?mode=ro", uri=True)
            try:
                df = pd.read_sql_query(EXTRACT_SQL, con, params=(order_date.isoformat(), tomorrow.isoformat()))
            finally:
                con.close()
            log.info("extract %s, rows: %d", order_date, len(df))
            return df
        except sqlite3.OperationalError as e:
            if attempt == ATTEMPTS:
                raise
            wait = 2 ** (attempt - 1)
            log.warning("extract failed (%s), attempt %d of %d, retrying in %ds", e, attempt, ATTEMPTS, wait)
            time.sleep(wait)

Transform with pandas

def transform(df: pd.DataFrame) -> pd.DataFrame:
    for row in df[df["paid_price"] != df["catalog_price"]].itertuples():
        log.warning("item %d: paid price %d, catalogue %d", row.item_id, row.paid_price, row.catalog_price)
    clean = df.drop_duplicates(subset=["order_id", "book_id"])
    if len(clean) < len(df):
        log.warning("doubled rows dropped: %d", len(df) - len(clean))
    created = pd.to_datetime(clean["created_at"])
    return pd.DataFrame({
        "order_id": clean["order_id"],
        "book_id": clean["book_id"],
        "order_date": created.dt.date,
        "week": created.dt.to_period("W").dt.start_time.dt.date,
        "city": clean["city"].fillna("Unknown"),
        "title": clean["title"],
        "qty": clean["qty"],
        "price": clean["catalog_price"],
    })

These are the steps from the pandas lesson, plus two checks that log a WARNING: a paid price that differs from the catalogue (item 16), and doubled lines (item 9). The function only takes a DataFrame and returns one, so it's easy to test without a database.

Checks like these can be made tidier with a validation library: Pydantic checks each record against a schema (types and rules per field), Great Expectations checks a whole table with declarative rules such as "price must be between 1 and 100". The details are in the Data Quality & Validation lesson.

Load: delete that date, then fill it

def load(df: pd.DataFrame, order_date: date) -> None:
    con = duckdb.connect(WAREHOUSE_DB)
    try:
        con.execute("""
            CREATE TABLE IF NOT EXISTS sales (
                order_id INTEGER, book_id INTEGER, order_date DATE, week DATE,
                city VARCHAR, title VARCHAR, qty INTEGER, price INTEGER)
        """)
        con.register("new_rows", df)
        con.begin()
        con.execute("DELETE FROM sales WHERE order_date = ?", [order_date])
        con.execute("INSERT INTO sales SELECT * FROM new_rows")
        con.commit()
        total = con.execute("SELECT COUNT(*) FROM sales").fetchone()[0]
        log.info("load %s, rows: %d, sales total: %d", order_date, len(df), total)
    finally:
        con.close()

A CLI and backfills

def run(order_date: date) -> None:
    load(transform(extract(order_date)), order_date)


def main() -> None:
    parser = argparse.ArgumentParser(description="Bookshop's daily sales load")
    parser.add_argument("order_date", type=date.fromisoformat, help="order date, YYYY-MM-DD")
    parser.add_argument("--until", type=date.fromisoformat, help="last date, for a backfill")
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S")

    day = args.order_date
    while day <= (args.until or args.order_date):
        run(day)
        day += timedelta(days=1)


if __name__ == "__main__":
    main()

Running it:

$ python pipeline.py 2026-10-01
21:24:23 INFO extract 2026-10-01, rows: 3
21:24:23 WARNING doubled rows dropped: 1
21:24:23 INFO load 2026-10-01, rows: 2, sales total: 2
$ python pipeline.py 2026-10-01
21:24:24 INFO extract 2026-10-01, rows: 3
21:24:24 WARNING doubled rows dropped: 1
21:24:24 INFO load 2026-10-01, rows: 2, sales total: 2
$ python pipeline.py 2026-09-28 --until 2026-10-09
21:24:25 INFO extract 2026-09-28, rows: 3
21:24:25 INFO load 2026-09-28, rows: 3, sales total: 5
...
21:24:25 INFO extract 2026-10-03, rows: 0
21:24:25 INFO load 2026-10-03, rows: 0, sales total: 9
...
21:24:25 INFO extract 2026-10-07, rows: 1
21:24:25 WARNING item 16: paid price 190, catalogue 19
21:24:25 INFO load 2026-10-07, rows: 1, sales total: 15
...
21:24:26 INFO load 2026-10-09, rows: 1, sales total: 18

The second run still has 2 rows, because the DELETE throws away the first run's rows before the INSERT. The 12-date backfill ends at 18 rows, 21 books, $444, the same as every earlier lesson; 1 October is loaded once more without doubling. 3 October had no orders: 0 rows is normal, not an error. Remove the DELETE from the script and the second run of 1 October logs sales total: 4.

When the source can't be opened:

$ SOURCE_DB=wrong.db python pipeline.py 2026-10-02
21:24:26 WARNING extract failed (unable to open database file), attempt 1 of 3, retrying in 1s
21:24:27 WARNING extract failed (unable to open database file), attempt 2 of 3, retrying in 2s
Traceback (most recent call last):
  ...
sqlite3.OperationalError: unable to open database file
$ echo $?
1

That exit code 1 matters: cron or Airflow (the next lesson) knows the run failed and can tell someone.

⚠️ Scripts that look fine but cause trouble

TL;DR: Bookshop's Python pipeline is one pipeline.py: extract with parameterised SQL (?) against the app's database for one date, transform with pandas (drop doubles, fill empty cities, catalogue price, week), load into sales in DuckDB with a DELETE of that date then an INSERT in one transaction, so a rerun still leaves 2 rows for 1 October. Config comes from environment variables (SOURCE_DB, WAREHOUSE_DB), each step is recorded by logging with a time and a level, extract is retried with 1 and 2 second backoff and then fails with exit code 1, and the date is a CLI argument so the backfill 2026-09-28 --until 2026-10-09 fills 18 rows. Validation can be tidied up with Pydantic (per record) or Great Expectations (per table).

⚡ Three functions, one date

Meaning: pipeline.py runs extract(order_date), transform(df), then load(df, order_date) for one date. The date is a CLI argument, not "yesterday" from the computer's clock, so any date can be loaded again, backfills included.

⚡ Config from the environment

Write:

SOURCE_DB = os.environ.get("SOURCE_DB", "shop.db")

Meaning: The value comes from an environment variable, or "shop.db" when it's absent. A laptop and a server just differ in their environment; the script is the same.

⚡ Delete that date, then fill it

Write:

con.begin()
con.execute("DELETE FROM sales WHERE order_date = ?", [order_date])
con.execute("INSERT INTO sales SELECT * FROM new_rows")
con.commit()
Guess first: 1 October is loaded twice. How many rows for that date are in sales?

Still 2. The DELETE throws away the first run's rows before the INSERT. Without the DELETE, it's 4.

Meaning: An idempotent pipeline: however many times it runs, the result is the same, with no duplicated data.

⚡ Fail clearly

Meaning: The extract is retried after 1 and then 2 seconds, then the script stops with exit code 1. That way cron or Airflow knows the run failed. Don't swallow errors with except Exception.

What you will learn