Reference library

Python Code Samples

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

46 matches
Observability & SRE easy

How to Redact Secrets from Log Messages in Python

Build a lightweight RedactingFormatter class that replaces sensitive tokens like passwords and API keys with [REDACTED] before log messages are printed.

redaction logging secrets
Python
class RedactingFormatter:
    def __init__(self, secrets):
        self.secrets = secrets

    def redact(self, message):
        for secret in self.secrets:
            message = message.replace(secret, "[REDACTED]")
        return message

    def format(self, record):
        message = record["message"]
        ret…
12 0 Open
Auth & security at scale easy

Enforce TLS 1.2 Minimum in Python

Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.

tls ssl security
Python
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…
13 0 Open
Auth & security at scale easy

Fetch Secrets from a Mock Secrets Manager in Python

Build a minimal in-memory secrets manager that stores and retrieves secret values, raising a KeyError for missing names.

secrets-management security mock
Python
import json

class SecretsManager:
    """Mock secrets manager that returns secrets from a local store."""
    
    def __init__(self, store=None):
        self.store = store or {
            "api_key": "mock-api-key-123",
            "db_password": "s3cret-p@ss",
            "jwt_secret": "dev-only-secret"
        }
…
16 0 Open
Auth & security at scale easy

How to Check Negotiated Cipher Suite in Python

Connect to a TLS server with Python's ssl module and print the negotiated protocol version and cipher suite details.

tls ssl security
Python
import ssl
import socket

def get_cipher_suites(hostname, port=443):
    context = ssl.create_default_context()
    context.set_ciphers("DEFAULT:@SECLEVEL=2")
    
    with socket.create_connection((hostname, port), timeout=5) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        …
17 0 Open
Auth & security at scale easy

How to Create Secure Session Cookies in Python with Secure, HttpOnly, and SameSite Flags

This code demonstrates how to create a secure session cookie using Python's stdlib, setting Secure, HttpOnly, and SameSite attributes to protect against common web vulnerabilities.

cookies session security
Python
import http.cookies
import secrets

class SessionManager:
    def __init__(self):
        self.cookie = http.cookies.SimpleCookie()

    def create_session_cookie(self, session_id=None):
        session_id = session_id or secrets.token_hex(16)
        self.cookie["session"] = session_id
        self.cookie["session"][…
14 0 Open
Auth & security at scale easy

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.

referrer security headers
Python
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…
15 0 Open
Auth & security at scale easy

How to Generate PKCE Code Challenge in Python

This Python script generates a PKCE code verifier and its corresponding S256 code challenge for secure OAuth2 authorization flows.

pkce oauth2 security
Python
import base64
import hashlib
import os
import secrets
import string

def generate_code_verifier(length=64):
    alphabet = string.ascii_letters + string.digits + "-._~"
    return "".join(secrets.choice(alphabet) for _ in range(length))

def generate_code_challenge(code_verifier, method="S256"):
    if method == "S256…
15 0 Open
Auth & security at scale easy

How to Generate and Verify HMAC Signatures in Python

Create and validate HMAC-SHA256 signatures with a shared secret key using Python's hmac and hashlib modules.

hmac security cryptography
Python
import hashlib
import hmac

SECRET_KEY = b"pepper-secret-2024"

def generate_hmac(message: str) -> str:
    return hmac.new(SECRET_KEY, message.encode("utf-8"), hashlib.sha256).hexdigest()

def verify_hmac(message: str, received_hmac: str) -> bool:
    expected = generate_hmac(message)
    return hmac.compare_digest(e…
15 0 Open
Auth & security at scale easy

How to Hash Passwords Securely in Python

Hash passwords with PBKDF2, random salts, and constant pepper, plus generate secure API keys using Python's stdlib.

password hashing security
Python
import hashlib
import secrets
import time
import hmac


def hash_password(password: str, salt: str = None, pepper: str = "static-pepper") -> dict:
    """Hash a password with a random salt and constant pepper."""
    if salt is None:
        salt = secrets.token_hex(16)
    salted = f"{pepper}{salt}{password}"
    dig…
15 0 Open
Auth & security at scale easy

How to Hash Passwords with bcrypt in Python

Hash a plaintext password with bcrypt using a randomly generated salt, then verify a plaintext attempt against the stored hash.

bcrypt password security
Python
import bcrypt

def hash_password(password: str) -> str:
    """Hash a password using bcrypt with a generated salt."""
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8")

def check_password(password: str, hashed: str) -> bool:
    """Verify a plaintext password against …
13 0 Open
Auth & security at scale easy

How to Hash and Verify Passwords in Python

Hash passwords securely with PBKDF2-SHA256 and verify them using a constant-time comparison.

password-hashing security pbkdf2
Python
import hashlib
import hmac
import secrets
from typing import Tuple


def hash_password(password: str, salt: str = None) -> Tuple[str, str]:
    """Hash a password with a random salt using PBKDF2-SHA256."""
    salt = salt or secrets.token_hex(16)
    hashed = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf…
14 0 Open
Auth & security at scale easy

How to Implement an HSTS Preload List Mock in Python

Implements a mock HSTS preload list in Python that supports adding, removing, checking domains with subdomain inheritance, and listing domains.

hsts security domains
Python
import json

class HSTSPreloadList:
    def __init__(self):
        self.domains = {}

    def add_domain(self, domain, include_subdomains=False, max_age=31536000):
        self.domains[domain] = {
            "include_subdomains": include_subdomains,
            "max_age": max_age
        }

    def remove_domain(sel…
15 0 Open
Auth & security at scale easy

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.

csp http-server security-headers
Python
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("…
15 0 Open
Auth & security at scale easy

How to Mock a Permissions Policy in Python

A lightweight Python class that simulates a browser Permissions-Policy header by tracking allowed/ denied feature permissions with get, set, reset, and bulk operations.

permissions-policy mock security
Python
class PermissionsPolicy:
    def __init__(self):
        self._features = {
            "geolocation": "self",
            "camera": "self",
            "microphone": "self",
            "payment": "self",
            "usb": "self",
        }

    def get_feature_policy(self, feature):
        return self._features.ge…
14 0 Open
Auth & security at scale easy

How to Revoke Tokens with a Blacklist Set in Python

A minimal TokenBlacklist class using a Python set to revoke, batch-revoke, check, and remove expired tokens for simple token invalidation.

jwt blacklist authentication
Python
import time

class TokenBlacklist:
    def __init__(self):
        self.blacklisted_tokens = set()

    def revoke(self, token):
        self.blacklisted_tokens.add(token)
        print(f"Token {token} revoked. Blacklist size: {len(self.blacklisted_tokens)}")

    def revoke_batch(self, tokens):
        before = len(s…
13 0 Open
Auth & security at scale easy

How to Salt Passwords per User in Python

Hash each user's password with a unique random salt using hashlib, and verify logins with timing-safe comparison.

password-hashing security authentication
Python
import hashlib
import secrets

def hash_password(password: str, salt: str | None = None) -> tuple[str, str]:
    """Hash a password with a random salt (or provided salt).

    Returns:
        (salt_hex, password_hash_hex)
    """
    if salt is None:
        salt = secrets.token_hex(16)
    salted = (salt + password)…
14 0 Open
Auth & security at scale easy

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.

flask security headers
Python
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…
12 0 Open
Auth & security at scale easy

How to Set a SameSite Cookie in Python

Set a SameSite cookie attribute in Python using the standard library's SimpleCookie class.

cookies samesite http
Python
from http.cookies import SimpleCookie

def set_same_site_cookie(name, value, same_site="Lax"):
    cookie = SimpleCookie()
    cookie[name] = value
    cookie[name]["path"] = "/"
    cookie[name]["samesite"] = same_site
    return cookie[name].OutputString()

if __name__ == "__main__":
    print(set_same_site_cookie("…
12 0 Open
Auth & security at scale easy

How to Verify Passwords in Constant Time in Python

Use hmac.compare_digest to verify passwords in constant time, preventing timing attacks that could reveal password length or character positions.

security authentication timing-attacks
Python
import hmac
import time

# Mock of a constant-time password comparison (prevents timing attacks)
def verify_password(stored_password: str, supplied_password: str) -> bool:
    # hmac.compare_digest runs in constant time (for a given length)
    return hmac.compare_digest(stored_password.encode(), supplied_password.enc…
16 0 Open
Auth & security at scale easy

How to mock short TTL access tokens in Python

Simulate short-lived access tokens with a TTL, issue and validate them, and watch expiry behavior.

auth tokens expiry
Python
import time
import uuid
from datetime import datetime, timedelta


class AccessTokenManager:
    def __init__(self, ttl_seconds=30):
        self.ttl_seconds = ttl_seconds
        self.tokens = {}

    def issue_token(self):
        token_id = uuid.uuid4().hex
        expiry = datetime.now() + timedelta(seconds=self.t…
15 0 Open
Production deployment patterns easy

How to Build a Mock Trivy Image Scan Gate in Python

Simulate a Trivy image scan and enforce a security gate that fails the pipeline when vulnerabilities meet or exceed a severity threshold.

trivy security ci-cd
Python
import json
import sys


def mock_trivy_scan(image_name, severity_threshold="HIGH"):
    """Simulate a Trivy image scan result."""
    mock_vulnerabilities = [
        {"ID": "CVE-2023-1234", "Severity": "HIGH", "Package": "openssl", "FixedVersion": "3.0.9"},
        {"ID": "CVE-2024-5678", "Severity": "CRITICAL", "Pa…
13 0 Open
Production deployment patterns easy

How to Mock Docker Image Non-Root User in Python

This Python class simulates Docker image layers and inspects whether the final user is a non-root user, returning UID, GID, and security status.

docker security mock
Python
from pathlib import Path


class DockerImageMock:
    def __init__(self, name, tag):
        self.name = name
        self.tag = tag
        self.layers = []
        self.user = "root"

    def add_file(self, path, content):
        self.layers.append({"file": path, "content": content})

    def set_user(self, usernam…
11 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.