Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Ship the whole system
EXPERIMENT 101 / 101

From a query to a decision.

Join storage, analysis, and Matplotlib without leaking connection ownership into rendering.

ADVANCED LAB / BUILD PROJECT
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

This final build keeps database retrieval and chart creation as separate phases. The query returns a bounded aggregate, the database connection closes, and the renderer works with ordinary values. That separation makes the reporting code easier to test, avoids holding database resources while exporting images, and makes it possible to replace the input adapter later.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

database_report_project.py
from lab_support import mysql_lab
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
with mysql_lab() as (connection, cursor):
    cursor.execute("SELECT p.name, SUM(t.minutes) AS minutes FROM lab_projects p JOIN lab_tasks t ON t.project_id = p.id WHERE t.done = %s GROUP BY p.id, p.name ORDER BY p.id", (False,))
    rows = [{"name": row["name"], "minutes": int(row["minutes"])} for row in cursor.fetchall()]
fig, ax = plt.subplots(figsize=(6, 3.5), layout="constrained")
ax.bar([row["name"] for row in rows], [row["minutes"] for row in rows], color="#ed5027")
ax.set(title="Unfinished effort by project", ylabel="Minutes", ylim=(0, 75))
fig.savefig("database-report-project.png", dpi=140, bbox_inches="tight")
plt.close(fig)
print([(row["name"], row["minutes"]) for row in rows])
↳ EXPECTED OUTPUT
[('Orbit', 60), ('Atlas', 30)]

03 Under the hood

  1. 1

    The SQL performs grouping close to the data. Only a small result crosses into Python, and values are converted into the application’s chosen types.

  2. 2

    The with block ends before plotting. The renderer should accept records as an argument rather than opening its own secret database connection.

  3. 3

    For a deployable version, add explicit configuration, CLI arguments, logging, tests for no data, and an output publication strategy. Then implement the same report using MongoDB aggregation and compare the fixture totals.

04 Your turn, builder

A SMALL MISSION

Build an equivalent project-total report from the MongoDB fixture, returning deterministic sorted pairs.

Reveal one possible solution +
one_possible_solution.py
from lab_support import mongo_lab
with mongo_lab() as collection:
    pipeline = [{"$match": {"done": False}}, {"$group": {"_id": "$project", "minutes": {"$sum": "$minutes"}}}, {"$sort": {"_id": 1}}]
    rows = [(row["_id"], row["minutes"]) for row in collection.aggregate(pipeline)]
print(rows)

↗ Definition of done

  • □Retrieve unfinished project totals through a parameterized query.
  • □Close the database scope before chart rendering.
  • □Export a chart with Orbit 60 and Atlas 30 minutes.
  • □Add no-data handling and an output path argument.
  • □Reproduce the totals with a MongoDB aggregation adapter.

05 Check your signal

QUICK SIGNAL CHECK

Why close the database scope before rendering?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.