Reference library

Python Code Samples

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

31 matches
Files & data easy

How to Extract IP Address Counts from Access Logs in Python

Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.

regex access log counter
Python
import re
from collections import Counter
from pathlib import Path

def extract_ip_counts(log_file_path):
    ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    ip_counter = Counter()
    
    with open(log_file_path, 'r') as file:
        for line in file:
            match = re.match(ip_pattern, line)
       …
17 0 Open
Automation & scripting easy

Create a Simple HTTP File Server in Python

This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.

http server file-server
Python
import http.server
import socketserver
import os

PORT = 8000
DIRECTORY = os.getcwd()

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def log_message(self, format, *args):
        print(f"[{self.log…
55 0 Open
Git + Python easy

Upload Assets to GitHub Release with Python Mock

Simulates uploading binary and text assets to a GitHub release using a mock server, returning structured metadata for each upload.

git github releases
Python
import json
import os
import tempfile
from datetime import datetime

class ReleaseUploader:
    """Simulates uploading assets to a release with a mock server."""
    
    def __init__(self, owner: str, repo: str, tag: str):
        self.owner = owner
        self.repo = repo
        self.tag = tag
        self.uploade…
12 0 Open
Cloud + Python easy

Mock Lambda handler event context dict in Python

Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.

lambda aws mock
Python
import json


def lambda_handler(event, context):
    """
    A mock AWS Lambda handler that processes an event dict and context object.
    Demonstrates the typical Lambda function signature and basic event/context usage.
    """
    print("Received event:", json.dumps(event, indent=2))
    print("Function name:", co…
14 0 Open
System design patterns easy

How to Build a Weighted Random Load Balancer in Python

A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.

python how build
Python
import random
from collections import Counter

SERVERS = {
    "server-a": 50,
    "server-b": 30,
    "server-c": 20,
}


def weighted_random_server(servers: dict[str, int]) -> str:
    """Select a server based on its weight (higher weight = more likely)."""
    total_weight = sum(servers.values())
    rand = random.…
13 0 Open
System design patterns easy

Observer Pattern with Mock Metrics in Python

Implement the Observer pattern with a mock metrics collector to track state changes and verify notifications.

observer mock design pattern
Python
import unittest
from unittest.mock import Mock


class Subject:
    def __init__(self):
        self._state = 0
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def set_state(self, value):
        if value != self._state:
            self._state = value
      …
12 0 Open
System design patterns easy

Round Robin Load Balancer in Python

This code simulates round robin load balancing by distributing a list of requests evenly across a list of servers.

load-balancing round-robin system-design
Python
def round_robin_servers(requests: list[str], servers: list[str]) -> dict[str, list[str]]:
    assignments = {server: [] for server in servers}
    for idx, request in enumerate(requests):
        server = servers[idx % len(servers)]
        assignments[server].append(request)
    return assignments


if __name__ == "_…
13 0 Open
API design & gRPC easy

How to Build a WebSocket Echo Server in Python with asyncio

Create a simple WebSocket echo server using the websockets library and asyncio to handle concurrent connections.

websockets asyncio server
Python
import asyncio
import websockets

async def echo(websocket):
    async for message in websocket:
        await websocket.send(f"Echo: {message}")

async def main():
    async with websockets.serve(echo, "localhost", 8765):
        print("WebSocket server started on ws://localhost:8765")
        await asyncio.Future() …
15 0 Open
API design & gRPC easy

How to Implement a REST DELETE Mock Server Returning 204 in Python

A minimal HTTP server mock that responds to DELETE requests with 204, 404, or 403 statuses based on the resource ID.

http-server rest mock
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

class MockHandler(BaseHTTPRequestHandler):
    def do_DELETE(self):
        if self.path.startswith("/api/resource/"):
            resource_id = self.path.split("/")[-1]
            if resource_id == "42":
                # Successful delete: 204 …
12 0 Open
API design & gRPC easy

How to Mock HTTP 304 Responses with If-None-Match in Python

Spin up a local HTTP server that returns a 304 Not Modified when a request carries a matching ETag, useful for testing cache behavior.

http caching mock-server
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import urllib.request

ETAG = '"abc123"'
BODY = b'{"status": "ok"}'

class MockServer(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.headers.get('If-None-Match') == ETAG:
            self.send_response(304)
        …
11 0 Open
API design & gRPC easy

How to Mock a GraphQL Query Type in Python

Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.

graphql mock resolver
Python
import json

class Query:
    def __init__(self):
        self.starred_repos = [
            {"id": 1, "name": "graphql", "owner": "graphql"}
        ]

    def repository(self, name):
        if name == "graphql":
            return {"id": 1, "name": "graphql", "stargazerCount": 85000}
        return None


if __name…
14 0 Open
API design & gRPC easy

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.

api authentication http
Python
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…
12 0 Open
API design & gRPC easy

How to Parse gRPC Request Data in Python

Build a beginner-friendly gRPC service handler that parses incoming protobuf messages into Python dictionaries and starts a simple gRPC server.

grpc protobuf api
Python
from google.protobuf import json_format
import grpc
from concurrent import futures
import time


class DataParsingService:
    def parse(self, request):
        return {
            "received_json": json_format.MessageToJson(request),
            "parsed_fields": {
                "name": request.name,
               …
14 0 Open
API design & gRPC easy

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.

cors http server
Python
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…
13 0 Open
API design & gRPC easy

How to mock a REST POST endpoint in Python

Create a simple mock REST server that responds to POST requests with a 201 status and a JSON body.

http mock api
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer


class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(content_length) if content_length else b"{}"
        try:
            data = json…
12 0 Open
API design & gRPC easy

Serve Swagger UI with Python's built-in HTTP server

Hosts a self-contained Swagger UI with a mock OpenAPI spec using only Python's standard library HTTP server.

swagger openapi http-server
Python
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import tempfile

SWAGGER_HTML = """<!DOCTYPE html>
<html>
<head>
    <title>Mock Swagger UI</title>
    <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4/swagger-ui.css">
</head>
<body>
    <div id="swagger-ui"></div>
    <script src…
14 0 Open
Streaming & messaging easy

Redis Pub/Sub Channel Subscribe Mock in Python

A lightweight in-memory mock of Redis pub/sub that lets you subscribe to channels, publish messages, and verify handler behavior in tests without a real Redis server.

redis pubsub testing
Python
class MockRedisPubSub:
    def __init__(self):
        self.channels = {}

    def subscribe(self, channel):
        if channel not in self.channels:
            self.channels[channel] = []
        return self.channels[channel]

    def publish(self, channel, message):
        if channel in self.channels:
            …
11 0 Open
Caching & Redis easy

Redis INCR DECR Counter Mock in Python

Simulate Redis INCR and DECR commands with a Python class to test counter logic without a live Redis server.

redis counter mock
Python
class RedisCounter:
    def __init__(self):
        self._store = {}

    def incr(self, key: str, amount: int = 1) -> int:
        if key not in self._store:
            self._store[key] = 0
        self._store[key] += amount
        return self._store[key]

    def decr(self, key: str, amount: int = 1) -> int:
     …
16 0 Open
Reliability & rate limiting easy

How to Stop Receiving Requests Until Ready in Python

A mock server that refuses requests until a readiness gate is passed, simulating fail-stop behavior for production reliability.

readiness fail-stop mock-server
Python
import random
import time


class MockServer:
    def __init__(self):
        self.ready = False
        self.requests_received = 0

    def readiness_check(self):
        """Simulates a readiness probe. Returns True only when ready."""
        if not self.ready:
            return False
        return True

    def r…
14 0 Open
Observability & SRE easy

How to Mock an OTLP HTTP Endpoint in Python

This code implements a lightweight HTTP server that accepts OTLP/HTTP trace exports, stores spans by trace ID, and exposes them via a simple GET endpoint for debugging.

otlp http mock
Python
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from collections import defaultdict

class TraceHandler(BaseHTTPRequestHandler):
    traces = defaultdict(list)

    def do_POST(self):
        if self.path == "/v1/traces":
            length = int(self.headers.get("Content-Length", 0))
 …
13 0 Open
Microservices patterns easy

Correlation ID HTTP header mock in Python

A lightweight HTTP server that echoes or generates correlation IDs to help test distributed systems.

correlation-id http-server mock
Python
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 = {
        …
13 0 Open
Microservices patterns easy

How to Mock Eventual Consistency UI Notes in Python

Simulates a UI note that shows local state until a pending server update is confirmed, mocking eventual consistency behavior in distributed systems.

eventual-consistency microservices ui
Python
class EventualConsistencyNote:
    def __init__(self, entity_id, note):
        self.entity_id = entity_id
        self.note = note
        self.confirmed = False
        self.pending_updates = []

    def add_pending_update(self, update):
        self.pending_updates.append(update)

    def confirm_update(self):
    …
17 0 Open
Microservices patterns easy

How to Mock Service Versioning URI in Python

Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.

http-server versioning mock
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json


class VersionedHandler(BaseHTTPRequestHandler):
    def _send_json(self, payload, status=200):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
    …
11 0 Open
Microservices patterns easy

How to Mock a Server-Side Load Balancer in Python

A simple Python class that mimics a server-side load balancer with round-robin, random, and least-connections selection strategies.

load-balancer microservices simulation
Python
import itertools
import random

class LoadBalancer:
    def __init__(self, servers=None):
        self.servers = servers if servers else ["server1", "server2", "server3"]
        self.counter = itertools.count(1)

    def round_robin(self):
        return next(self.counter) % len(self.servers)

    def random_selectio…
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.