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.
1. Real-World Backend Capstone
Every backend, DevOps, and data engineer regularly builds two kinds of production utilities:
- 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. - 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.
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):
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})): Readingm.group("status")andm.group("path")is self-documenting and far less brittle than positionalm.group(4)indices. - Lazy Backpressure (
yield+Counter):Counterpulls 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 topkoffenders cleanly inO(U log k)time, whereUis 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:
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
- Never omit
timeout=: By default,requests.get()waits forever if a remote server stalls, hanging your entire worker thread. - Pass query parameters via
params={}: Never glue user input onto URLs with f-strings —params={}handles URL-encoding safely and prevents malformed query bugs. - Reuse
requests.Session()for repeated calls: If you fetch weather for 50 cities in a loop, wrapping calls inwith requests.Session() as session:reuses the underlying TCP/TLS connection (HTTP keep-alive), cutting latency dramatically.
4. Interactive Trace: Streaming Log Lines → Regex → Counter
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:
- Master relational databases and backend query tuning with our Free SQL & Databases A–Z Course (24 Visual Lessons) — featuring clause-by-clause interactive SQL tracers and PostgreSQL/MySQL deep dives.
- Ready to crack product-company coding interviews using your new Python skills? Jump into the Visual DSA Mastery Roadmap (23 Modules · 94 Problems).
- Bookmark our 12 Free Privacy-First Browser Developer Tools (Regex Tester, JSON Formatter, Base64 Encoder, JWT Decoder, Diff Checker, Big-O Calculator & more — 100% client-side with zero uploads).
Final Capstone Quiz: Module 10.2 — Production Python
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.