Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Use Redis as a Cache in Python
A beginner-friendly RedisCache helper that stores, retrieves, and deletes JSON values with automatic TTL expiration using the redis-py client.
import json
import time
import redis
class RedisCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def set(self, key, value, ttl=None):
"""Store a v…
How to Implement a Token Bucket Rate Limiter per Client IP in Python
Implements a simple sliding-window rate limiter using a dictionary of timestamp lists per client IP to limit requests per window.
from time import time
from collections import defaultdict
class RateLimiter:
def __init__(self, max_requests: int, window_seconds: int):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.clients = defaultdict(list)
def allow(self, ip: str) -> bool:
now…
How to Mock HTTP Client Latency in Python
Simulate outbound HTTP request latency with configurable ranges to test timeouts, retries, and SLO monitoring without external services.
import time
import random
def mock_latency(host: str, min_ms: int = 100, max_ms: int = 500) -> dict:
"""Simulate an outbound HTTP request with mock latency."""
latency_ms = random.randint(min_ms, max_ms)
start = time.perf_counter()
time.sleep(latency_ms / 1000)
elapsed_ms = (time.perf_counter() - …
How to Build an OAuth Client Credentials Mock Server in Python
A minimal HTTP mock server implementing the OAuth 2.0 client credentials grant for local testing and microservice development.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
TOKENS = {"valid_token": "demo_access_token", "client_id": "my_service"}
class OAuthHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/oauth/token":
length = int(self.headers.get("Content-Length", 0))
…
How to implement round-robin load balancing in Python
Implement a client-side round-robin load balancer that distributes requests sequentially across a list of mock servers using itertools.cycle.
import itertools
import random
class MockServer:
def __init__(self, name):
self.name = name
def handle_request(self, request_id):
return f"Server {self.name} handled request #{request_id}"
class RoundRobinLoadBalancer:
def __init__(self, servers):
self.servers = servers
…
How to mock an external service in Python with an anti-corruption facade
This code implements an anti-corruption facade that mocks an external API, allowing client code to interact with a simulated service while keeping the same interface.
class AntiCorruptionFacade:
"""Mocks a real API while keeping the same interface."""
def __init__(self, data_store):
self._data_store = data_store
self._calls = []
def get_user(self, user_id):
self._calls.append(f"get_user({user_id})")
return self._data_store.get(u…
How to Build a DAG Execution Stage Calculator in Python
Computes the execution stages of a directed acyclic graph (DAG) by grouping nodes that become ready simultaneously using topological sorting with Kahn's algorithm.
from collections import defaultdict, deque
def get_stages(edges):
"""Return list of stages, where each stage is a list of nodes
that become ready at the same time in a DAG."""
graph = defaultdict(list)
in_degree = defaultdict(int)
nodes = set()
for src, dst in edges:
graph[src].appen…
How to Mock MLflow Model Registration in Python
Build a lightweight in-memory mock of MLflow's MlflowClient to test model registration, versioning, and stage transitions without a tracking server.
from mlflow.tracking import MlflowClient
from mlflow.entities import ModelVersion, Model
class MockMlflowClient:
"""Minimal mock of MlflowClient's model registration methods."""
def __init__(self):
self.registered_models = {}
self.model_versions = {}
def register_model(self, mod…
Enforce TLS 1.2 Minimum in Python
Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.
import ssl
def get_min_tls_version():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context.minimum_version
if __name__ == "__main__":
min_version = get_min_tls_version()
print(f"Minimum TLS version set to: {min_version.name} (value: {mi…
How to Mock an mTLS Client Certificate in Python
Create a self-signed client certificate and key with OpenSSL, load them into an SSL context, and simulate an mTLS handshake in Python for testing.
import ssl
import socket
import subprocess
import tempfile
from pathlib import Path
def create_mock_certificates():
"""Generate self-signed client certificate and key for mTLS testing."""
with tempfile.TemporaryDirectory() as tmpdir:
cert_path = Path(tmpdir) / "client.crt"
key_path = Path(tmpd…
How to Set X-Frame-Options DENY in Flask with a Mock Response
Set the X-Frame-Options header to DENY in a Flask response to prevent clickjacking, and verify it with Flask's test client.
from flask import Flask, Response
app = Flask(__name__)
@app.route("/")
def index():
response = Response("Hello, World!")
response.headers["X-Frame-Options"] = "DENY"
return response
if __name__ == "__main__":
with app.test_client() as client:
resp = client.get("/")
print(resp.get_da…
Mock client credentials machine auth in Python
This code simulates the OAuth2 client-credentials flow for service-to-service calls, generating a mock bearer token with expiry and caching, plus a revoke method, using only the standard library.
import time
import hashlib
import secrets
class MachineAuth:
"""Mock client-credentials machine auth for service-to-service calls."""
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
self._token = None
self._expire…
How to Mock Kubernetes Secret Mounts in Python
Create and inspect a mock Kubernetes secret volume mount using the official client library and unittest.mock.
import json
from kubernetes import client, config, watch
from unittest.mock import Mock, patch
def create_mock_mount_spec():
"""Create a mock Kubernetes secret volume mount."""
mock_client = Mock()
mock_client.api_version = "v1"
mock_client.kind = "Secret"
mock_client.metadata = {"name": "my-secre…
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.