Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Implement Bulkhead Thread Pool Isolation in Python
Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.
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 = …
How to Add a Correlation ID Tracing Header in Python
A mock middleware generates or preserves a correlation ID header and logs structured JSON messages with it for API request tracing.
import uuid
import json
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Request:
headers: dict = field(default_factory=dict)
def get(self, key, default=None):
return self.headers.get(key, default)
class CorrelationIdMiddleware:
def __init__(self, header_name…
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.
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")
…
How to Decode Basic Auth Credentials in Python
Decode username and password from a Basic Auth header string using base64 and standard string operations.
import base64
def decode_basic_auth(header_value):
"""
Decode credentials from a Basic Auth header value.
Expected format: "Basic base64encoded(username:password)"
Returns a tuple (username, password).
"""
if not header_value.startswith("Basic "):
raise ValueError("Invalid Basic A…
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.
```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 …
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.
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…
How to Mock Content-Disposition and Extract Filename in Python
Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.
import os
from pathlib import Path
import re
from unittest.mock import patch
def get_filename_from_content_disposition(header_value):
"""
Extract filename from a Content-Disposition header value.
Supports both filename and filename* parameters (RFC 5987).
"""
if not header_value:
return No…
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.
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)
…
How to Mock an API Key Header Authentication Server in Python
A minimal HTTP server that validates requests using an X-API-Key header and returns JSON responses for authenticated and unauthenticated calls.
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
API_KEYS = {"test-user": "secret-key-123"}
class AuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
auth = self.headers.get("X-API-Key")
if not auth or auth not in API_KEYS.values():
self.send_response…
How to handle CORS preflight OPTIONS requests in Python
Create a mock HTTP server with a CORS preflight OPTIONS handler that returns the correct headers for browser-based API requests.
from http.server import BaseHTTPRequestHandler, HTTPServer
class CORSRequestHandler(BaseHTTPRequestHandler):
def _send_cors_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
self.send_head…
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.
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…
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.
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 = "…
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.
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:
…
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.
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)")
…
How to Generate and Propagate W3C Trace Context Headers in Python
Generate and propagate W3C traceparent and tracestate headers for distributed tracing in Python, with mock service headers.
import uuid
def generate_w3c_traceparent(trace_id=None, parent_id=None, flags="01"):
if trace_id is None:
trace_id = uuid.uuid4().hex[:32]
if parent_id is None:
parent_id = uuid.uuid4().hex[:16]
return f"00-{trace_id}-{parent_id}-{flags}"
def create_mock_headers(service_name, trace_id=N…
How to Simulate Trace Sampling Head in Python
Simulate head-based probabilistic trace sampling on mock trace data with a configurable sample rate and optional seed for reproducibility.
import random
def trace_sampling_head(mock_traces, sample_rate=0.5, seed=None):
"""Simulate probabilistic trace sampling (head-based) on mock data.
Args:
mock_traces: list of trace dictionaries with a unique 'trace_id'
sample_rate: float 0.0-1.0, probability of keeping a trace
see…
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.
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…
Correlation ID HTTP header mock in Python
A lightweight HTTP server that echoes or generates correlation IDs to help test distributed systems.
import json
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
class CorrelationHandler(BaseHTTPRequestHandler):
CORRELATION_HEADER = "X-Correlation-ID"
def do_GET(self):
correlation_id = self.headers.get(self.CORRELATION_HEADER) or str(uuid.uuid4())
response = {
…
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.
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…
How to Load CSV Training Data in Python Without Pandas
Load CSV training data using Python's standard library and mock it with io.StringIO for testing, returning headers and rows as dictionaries.
import csv
from pathlib import Path
def load_csv_training_data(file_path: str | Path) -> tuple[list[str], list[dict[str, str]]]:
"""Load CSV training data and return headers plus rows as dictionaries."""
with open(file_path, mode="r", newline="", encoding="utf-8") as csv_file:
reader = csv.DictReader…
How to Enforce a Strict Referrer Policy in Python
Validate HTTP headers to enforce a strict same-origin Referrer policy, accepting only origin-only URLs or absent Referer values.
import re
from unittest.mock import patch
def strict_referrer_policy(headers):
"""Return True if Referer header is absent or strictly same-origin."""
referer = headers.get("Referer")
if referer is None:
return True
# Strict-Origin-When-Cross-Origin allows same-origin full URL
# but here we…
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.
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()
…
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.
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)
…
How to Mock a Content Security Policy Header in Python
Mock a Content-Security-Policy header locally and verify it's served correctly using Python's built-in HTTP server.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
CSP_HEADER = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
class MockServer(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.