सामग्री पर जाएँ

लेसन 19 · Automating Reports

Generating Reports with Python

Build a small Python report pipeline with the standard library: read CSV data, validate it, calculate metrics and render safe text, CSV and HTML output.

Copying numbers by hand each week is slow and error-prone. A script does the same steps in the same order every time, and it leaves a record of the rules in code. In this lesson you build a small pipeline with Python's standard library. Larger projects often use libraries such as pandas and templating or spreadsheet tools, but the structure stays the same.

The pipeline shape

flowchart LR
  A["Load"] --> B["Validate"]
  B --> C["Calculate"]
  C --> D["Render"]
  D --> E["Check and deliver"]

Each step has one job, so you can test it on its own.

Keep calculation separate from rendering. Calculation returns numbers. Rendering turns numbers into text. Then you can test the math without reading output, and add a new format without touching the math.

Load and validate

Real input has surprises. Check it before you calculate. Decide for each problem whether to stop the report or to skip and count the row. A silent skip is the worst choice.

Python Load CSV data and report bad rows

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In your own project, a missing region might be kept under "(not recorded)" instead of rejected. The point is to decide, write the rule down and count the affected rows. In code that handles real money, use decimal.Decimal instead of float.

Calculate, then render

The next block calculates results as plain data, then renders them as a text report and as CSV for spreadsheet users.

Python Calculate once, render twice

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Render safe HTML

When data goes into HTML, escape it. A product or customer name that contains < or & can break the page, and untrusted text can inject scripts. html.escape handles text placed between tags and inside quoted attributes.

Python An HTML table with escaped text

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Spreadsheet programs have a similar risk. A text cell in a CSV file that begins with =, +, - or @ may be treated as a formula when opened. If values come from users, neutralize them according to your security team's guidance.

Make runs repeatable

  • Pass the period in as a parameter. Do not hide "today" deep in the code, or you cannot rerun last week's report.
  • Record metadata: run time, period, data timestamp, row counts and code version.
  • Keep configuration outside the code, and keep passwords and API keys out of both the code and the repository. Use your platform's secret store or environment variables.
  • Make reruns safe. Running twice for the same period should replace or clearly version the output, not create confusing duplicates.
  • Test the calculation with tiny hand-made inputs whose answers you know.
TEXT
# Example run metadata saved beside each output (illustrative)
report: weekly_sales
period: 2026-11-23 to 2026-11-29 (UTC)
generated: 2026-11-30T06:00:00Z
rows_in: 4182   rows_rejected: 3
code_version: 7f3c1a2

Reading from a database

In a real job, the load step usually runs a query with a database library. The standard sqlite3 module and other drivers support parameter placeholders, which you should always use for values. This read-only sketch shows the idea.

Python
# Read-only: needs a real database file
import sqlite3

con = sqlite3.connect("file:warehouse.db?mode=ro", uri=True)
query = "SELECT region, amount FROM sales WHERE sold_at >= ? AND sold_at < ?"
data = con.execute(query, ("2026-11-23", "2026-11-30")).fetchall()
con.close()

Test the calculation

A report script needs tests like any other program. Choose input so small that you can work out the answer by hand, and include the awkward cases: no rows at all, only refunded rows and a single region. The assert statement is enough to show the idea, while a real project would normally use a test framework.

Python Small tests for a calculation

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that an empty input gives a total of 0 but a share of None. A total of nothing is zero, while a share of nothing is undefined. Your renderer should print "n/a" for the second case. It should also say clearly when there were no rows, because an empty week may be a real result or a failed load.

Test the renderer separately. Give it a hand-written result with a zero total, a very long name and a negative value, and read the output. A calculation test cannot tell you that a column has shifted or that a heading names the wrong period.

Organize the project

As the script grows, split it into files that follow the pipeline: one for loading, one for checks, one for calculations and one for rendering, plus a short main program that connects them. Keep tests and made-up sample input next to the code. Add a short note that explains how to run a past period and which settings are required.

Record the versions of any libraries you add, so that an upgrade does not change output unnoticed. Write logs that say what happened, with counts and the period, but do not write personal data or secrets into them. When a run fails, the message should tell the next person which step failed and what to check first. Avoid catching every error and carrying on, because that can publish a partial report that looks complete.

Know when to use a library

The standard library is enough for the small examples here and for many modest reports. Consider added libraries when you need spreadsheet files with formatting, charts, document layouts or fast work on large tables. Choose well-maintained ones that your organization allows, and keep your calculation tests when you switch. A library changes how the work is done, but not which definitions, checks and approvals the report needs. If a spreadsheet or reporting tool already does the job reliably and your team can maintain it, a custom script may not be worth its upkeep.

An automated script repeats its mistakes perfectly, every week. Add checks that can stop publication, which the later lessons on scheduling and on checking numbers cover.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why keep calculation separate from rendering?

    Separate steps are easier to test and to extend.
  2. 2. A row has an amount of 'abc'. What is the worst response?

    A silent skip changes totals without anyone knowing.
  3. 3. What should you do with names that go into an HTML report?

    Escaping stops special characters from breaking the page or injecting code.
  4. 4. Why pass the reporting period as a parameter?

    A period parameter makes runs repeatable and testable.

Summary

  • Build a pipeline of load, validate, calculate, render and deliver.
  • Decide how to treat bad rows, and always count them.
  • Return numbers from calculations and format only when rendering.
  • Escape text in HTML and take care with CSV formulas.
  • Parameterize the period, record metadata, protect secrets and test.

Next: Scheduling and Delivery

आपकी प्रगति इसी ब्राउज़र में सेव होती है। खाते की ज़रूरत नहीं है।