Python · Module 10: Hands-On Mini-ProjectsTutorial 30 of 30
All Tutorials·~2.5 hrs

10.2 Project 2: Streaming Log Analyzer & Weather API Client

Your final Python A–Z capstone! Build a memory-efficient streaming server log analyzer (Generators + Regex + Counter) paired with a live REST API client — and discover your next steps on BigOSlate.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Real-World Backend Capstone

Every backend, DevOps, and data engineer regularly builds two kinds of production utilities:

  1. Log & Data Pipelines that stream multi-gigabyte server logs without blowing up memory, extract structured fields with Regex, and surface the top failing endpoints with collections.Counter.
  2. Resilient REST API Clients that query external HTTP services safely with timeouts, status checks, and clean JSON parsing.

In this final capstone, you will combine Generators (yield), Compiled Regex, Counter, pathlib, and requests into two compact, production-grade tools.

Visual: Clean Real-World Python Project Architecture (Separation of Concerns)
1. Input / CLIArgs, User Prompt2. Models@dataclass + Types3. Core LogicPure Functions + Tests4. Storage / APIJSON / HTTP + Errors

2. Part A: Constant-Memory Streaming Log Analyzer

A classic beginner mistake is calling log_file.read_text().splitlines() on a production Nginx or API access log. That works fine on a 50 KB sample file on your laptop — and immediately triggers an OOMKilled crash when pointed at a 15 GB production log!

Instead, this pipeline streams the file one line at a time using a Python generator (yield). Whether the log file is 10 KB or 50 GB, file-reading RAM stays completely flat at O(1):

PYTHON
from collections import Counter
from pathlib import Path
import re
from typing import Iterator

LOG_PATTERN = re.compile(
    r"^(?P<date>\d{4}-\d{2}-\d{2})\s+(?P<level>INFO|WARN|ERROR)\s+(?P<path>/\S+)\s+(?P<status>\d{3})$"
)

def stream_error_paths(log_file: Path) -> Iterator[str]:
    """Lazily yields failing 5xx endpoint paths without loading the whole file into RAM."""
    with log_file.open("r", encoding="utf-8") as f:
        for line in f:
            m = LOG_PATTERN.match(line.strip())
            if m and int(m.group("status")) >= 500:
                yield m.group("path")

def top_failing_endpoints(log_file: Path, top_k: int = 3) -> list[tuple[str, int]]:
    counts = Counter(stream_error_paths(log_file))
    return counts.most_common(top_k)

Why Every Line Here Reflects Production Python

  • Pre-compiled Regex (re.compile): Compiling the pattern once at module import avoids re-compiling it millions of times inside the loop.
  • Named Capture Groups ((?P<status>\d{3})): Reading m.group("status") and m.group("path") is self-documenting and far less brittle than positional m.group(4) indices.
  • Lazy Backpressure (yield + Counter): Counter pulls paths one by one from the generator and only keeps a dictionary of unique failing endpoints in memory — turning a multi-gigabyte scan into a few kilobytes of RAM.
  • Top-K Ranking (most_common(top_k)): Under the hood, Counter.most_common(k) uses a min-heap (heapq.nlargest) to return the top k offenders cleanly in O(U log k) time, where U is the number of unique endpoints.

3. Part B: Production-Safe Weather API Client (Open-Meteo — Zero API Key Needed!)

Calling an external HTTP API looks simple until the remote server hangs for 60 seconds, returns HTTP 503 Service Unavailable, or drops the connection mid-response. Always guard external calls with explicit timeouts, raise_for_status(), and structured params={} encoding:

PYTHON
import requests

def get_current_weather(lat: float, lon: float) -> dict:
    try:
        resp = requests.get(
            "https://api.open-meteo.com/v1/forecast",
            params={"latitude": lat, "longitude": lon, "current_weather": "true"},
            timeout=5,
        )
        resp.raise_for_status()
        return resp.json()["current_weather"]
    except requests.RequestException as err:
        raise RuntimeError(f"Weather API request failed: {err}") from err

if __name__ == "__main__":
    weather = get_current_weather(12.97, 77.59)   # Bengaluru
    print(f"Temp: {weather['temperature']}°C | Wind: {weather['windspeed']} km/h")

3 Production API Habits to Carry Into Every Job

  1. Never omit timeout=: By default, requests.get() waits forever if a remote server stalls, hanging your entire worker thread.
  2. Pass query parameters via params={}: Never glue user input onto URLs with f-strings — params={} handles URL-encoding safely and prevents malformed query bugs.
  3. Reuse requests.Session() for repeated calls: If you fetch weather for 50 cities in a loop, wrapping calls in with requests.Session() as session: reuses the underlying TCP/TLS connection (HTTP keep-alive), cutting latency dramatically.

4. Interactive Trace: Streaming Log Lines → Regex → Counter

Tracing the Streaming Log Analyzer Pipeline
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→lines = ["2026-11-20 INFO /home 200", "2026-11-20 ERROR /pay 503", "2026-11-20 ERROR /pay 500"]
2errors = (parse_path(l) for l in lines if is_5xx(l))
3top = Counter(errors).most_common(1)
4print("Top failing endpoint:", top)
Variables in Memory
lines3 server log lineslist
Console Output
(nothing printed yet)
What just happened: Simulates streaming 3 log entries from a web server access log.

5. Congratulations — You Completed the Complete Python A–Z Course!

You went from writing your very first print("Hello!") all the way to object memory models, data structures, closures, OOP, generators, decorators, regex, asyncio, REST APIs, pytest, and two production-ready projects.

Where to go next on BigOSlate:


Final Capstone Quiz: Module 10.2 — Production Python

Q1.Why did `stream_error_paths()` use `yield` instead of building and returning a `list`?
Q2.Why did we pass query parameters via `params={...}` in `requests.get()` instead of gluing them onto the URL string?
Q3.What does `Counter(['/a', '/b', '/a']).most_common(1)` return?

Keep Exploring: Related Lessons & Tools

All Courses →