Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

21 matches
Files & data medium

Create a Python Tool That Generates Professional Excel Dashboards

Generate a professional sales dashboard in an Excel workbook with styled headers, a bar chart, and formatted number cells using the openpyxl library.

openpyxl excel dashboard
Python
import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter

def create_sales_dashboard(workbook_path: str) -> None:
    """Generate a professional sales dashboard in an Excel workbook."""
    wb = op…
49 0 Open
Files & data medium

Generate a Monthly Calendar PDF in Python

Create a Python utility that generates a monthly calendar PDF using ReportLab, with weekday headers and day numbers laid out in a grid.

calendar pdf reportlab
Python
from calendar import TextCalendar
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os

def generate_monthly_calendar_pdf(year, month, filename="calendar.pdf"):
    cal = TextCalendar()
    days = cal.monthdays2calendar(year, month)
    
    month_name …
1767 0 Open
Files & data medium

How to Scrape Headlines from a News Website Using Beautiful Soup in Python

Scrape headline text from a news website using requests and Beautiful Soup with a CSS selector.

web scraping beautifulsoup requests
Python
import requests
from bs4 import BeautifulSoup

def scrape_headlines(url: str, selector: str) -> list:
    """
    Scrape headlines from a news website using Beautiful Soup.
    
    Args:
        url: The URL of the news website.
        selector: CSS selector for headline elements.
    
    Returns:
        List of h…
56 0 Open
Automation & scripting medium

Automatically Generate Charts from CSV Files with One Command

Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.

csv matplotlib charting
Python
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt

def generate_chart(csv_path: str) -> None:
    """Read a CSV file with headers and plot the first two numeric columns."""
    data = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.reader(f)
        headers = next(re…
65 0 Open
Automation & scripting medium

Build a Website Accessibility Scanner Using Python

Scans a webpage for common accessibility issues like missing alt text, headings, labels, and landmarks using only Python.

accessibility a11y html
Python
import requests
from urllib.parse import urljoin
from html.parser import HTMLParser
import re

class AccessibilityParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.images_without_alt = []
        self.missing_headings = True
        self.has_main_tag = False
        self.label_for_inp…
40 0 Open
Automation & scripting medium

Create a Python Script That Detects Website Technology Stack Automatically

This script sends an HTTP request to a URL and inspects headers and HTML content to identify technologies like servers, frameworks, and JavaScript libraries.

requests web scraping tech stack
Python
import requests
from re import search

def detect_tech_stack(url):
    tech_stack = []
    try:
        response = requests.get(url, timeout=5, headers={'User-Agent': 'Mozilla/5.0'})
        headers = response.headers
        html = response.text.lower() if response.text else ''

        # Check server header
        …
43 0 Open
Automation & scripting medium

Find Broken Image References Across a Website in Python

Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.

web scraping crawling broken links
Python
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed

def find_all_links(base_url, max_pages=50):
    visited, to_visit = set(), {base_url}
    while to_visit and len(visited) < max_pages:
        url = to_visit.pop()
 …
39 0 Open
System design patterns medium

Implement Bulkhead Thread Pool Isolation in Python

Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.

bulkhead threadpool concurrency
Python
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor


class Bulkhead:
    """Simple bulkhead isolation: separate thread pools for different tasks."""

    def __init__(self, max_workers):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)
        self.active = …
13 0 Open
API design & gRPC medium

How to Build an Idempotency-Key POST Handler in Python

Python HTTP server mock that accepts POST requests and deduplicates them using an Idempotency-Key header, returning the same response for repeated calls.

http-server idempotency api-mock
Python
import hashlib
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse


class MockAPI(BaseHTTPRequestHandler):
    responses = {}

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length).decode("utf-8")
…
14 0 Open
API design & gRPC medium

How to Handle Retry-After Header in Python

Parse the Retry-After header from rate-limited API responses and implement retry logic with proper delays in Python.

retry-after api rate-limiting
Python
```python
import time
from datetime import datetime, timedelta


class RetryAfterHandler:
    def __init__(self, max_retries=3):
        self.max_retries = max_retries

    def get_retry_after_seconds(self, response_headers):
        retry_after_value = response_headers.get("Retry-After")
        if retry_after_value …
14 0 Open
API design & gRPC medium

How to Implement Content Negotiation with JSON and XML in Python

Build an HTTP server that returns JSON or XML responses based on the client's Accept header, with a 406 response for unsupported formats.

http-server content-negotiation json
Python
import json
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, HTTPServer


class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        data = {"message": "Hello, world!"}
        accept_header = self.headers.get("Accept", "")

        if "application/json" in accept_hea…
11 0 Open
API design & gRPC medium

How to Mock X-RateLimit Headers in Python

This code creates a local HTTP server that mimics rate limit headers (X-RateLimit-Limit, Remaining, Reset, Update) and returns 429 responses when the limit is exceeded.

http rate-limit server
Python
import time
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer


class RateLimitHandler(BaseHTTPRequestHandler):
    RATE_LIMIT = 5          # max requests allowed
    WINDOW_SECONDS = 60     # per time window

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
…
14 0 Open
API design & gRPC medium

Implement If-Match Precondition Update in Python

A mock resource store that uses the If-Match header's ETag to guard updates, preventing overwrites from stale clients.

api etag optimistic-concurrency
Python
from dataclasses import dataclass
from typing import Optional


@dataclass
class Resource:
    id: str
    version: int = 1
    data: str = ""
    etag: str = "etag-1"


class MockResourceStore:
    def __init__(self):
        self.resources = {}

    def update(self, resource_id: str, new_data: str, if_match: Optiona…
13 0 Open
API design & gRPC medium

Version API by Accept Header with Vendor Media Types in Python

Build a mock HTTP server that routes to API versions by parsing vendor-specific Accept headers in Python.

api-versioning accept-header http-server
Python
from http.client import HTTPMessage
from http.server import BaseHTTPRequestHandler, HTTPServer


class VendorVersionHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        accept = self.headers.get("Accept", "")
        version = "v1"
        if "application/vnd.myapi.v2+json" in accept:
            version = "…
13 0 Open
Reliability & rate limiting medium

How to Implement a Bulkhead Pattern with Threading in Python

Implement a bulkhead pattern in Python that isolates concurrent tasks with a bounded semaphore, limiting active workers to prevent resource exhaustion.

bulkhead threading semaphore
Python
import threading
import time
import random


class Bulkhead:
    def __init__(self, workers: int):
        self._semaphore = threading.BoundedSemaphore(workers)
        self._lock = threading.Lock()
        self._active = 0

    def run(self, task):
        with self._semaphore:
            with self._lock:
          …
13 0 Open
Observability & SRE medium

How to Create a TCP DNS Mock Server in Python

This code creates a mock TCP DNS server that listens on a specified port, accepts probe connections, and returns a fixed DNS response header to simulate a live DNS service for testing and observability.

socket dns tcp
Python
import socket
import threading


def handle_client(client_socket, address):
    print(f"[+] Connection from {address}")
    try:
        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            print(f"[*] Received {len(data)} bytes (TCP DNS probe)")
          …
16 0 Open
Microservices patterns medium

Bulkhead Thread Pool per Service Mock in Python

Simulates a bulkhead pattern with per-service thread pools and semaphore-based rejection to isolate failures between dependent services.

bulkhead threadpool semaphore
Python
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor

class ServiceBulkhead:
    def __init__(self, name, max_threads, max_queue):
        self.name = name
        self.executor = ThreadPoolExecutor(max_workers=max_threads)
        self.semaphore = threading.Semaphore(max_thread…
12 0 Open
Big data & Spark medium

How to Simulate a MapReduce Mock with Combine Phase in Python

Simulates a MapReduce pipeline with a combiner that aggregates local counts per reducer to reduce network and compute overhead.

mapreduce combiner hadoop
Python
from collections import defaultdict

def map_phase(lines):
    intermediate = defaultdict(list)
    for line in lines:
        for word in line.strip().lower().split():
            intermediate[word].append(1)
    return dict(intermediate)

def combine_phase(intermediate, num_reducers=3):
    combined = defaultdict(li…
14 0 Open
Auth & security at scale medium

How to Mock HTTP Responses to Verify HSTS Headers in Python

This code demonstrates how to use unittest.mock to intercept and capture HTTP response headers, specifically the Strict-Transport-Security header, from a mocked HTTPServer handler for security validation.

hsts mock security
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest.mock import patch

class StrictTransportMock(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
        self.end_headers()
  …
13 0 Open
Auth & security at scale medium

How to Mock a CORS Allow Origin Whitelist in Python

A decorator-based mock of a CORS middleware that whitelists allowed origins and injects proper Access-Control-Allow-Origin headers while rejecting others.

cors security middleware
Python
from functools import wraps


class MockCORSConfig:
    def __init__(self, allowed_origins):
        self.allowed_origins = allowed_origins

    def is_origin_allowed(self, origin):
        return origin in self.allowed_origins


def cors_middleware(config):
    def decorator(handler):
        @wraps(handler)
        …
16 0 Open
Auth & security at scale medium

How to Test X-Content-Type-Options nosniff in Python with Mocks

Mock httpx responses and verify that a server's X-Content-Type-Options header includes nosniff to prevent MIME sniffing.

security httpx mocking
Python
import httpx
from unittest.mock import Mock, patch

def fetch_headers(url: str) -> dict:
    response = httpx.get(url)
    return dict(response.headers)

def mock_nosniff_check(response) -> bool:
    content_type = response.headers.get("content-type", "")
    x_content_type_options = response.headers.get("x-content-ty…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.