Reference library

Python Code Samples

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

12 matches
Automation & scripting easy

How to generate an htpasswd bcrypt entry in Python

Create a mock htpasswd file entry with a bcrypt-hashed password for a given username using a simple Python script.

bcrypt htpasswd password
Python
import bcrypt

def mock_htpasswd_entry(username, password):
    salt = bcrypt.gensalt(rounds=12)
    hashed = bcrypt.hashpw(password.encode(), salt).decode()
    return f"{username}:{hashed}"

if __name__ == "__main__":
    entry = mock_htpasswd_entry("demo_user", "s3cretP@ss")
    print(entry)
15 0 Open
API design & gRPC easy

How to Decode Basic Auth Credentials in Python

Decode username and password from a Basic Auth header string using base64 and standard string operations.

base64 authentication api
Python
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…
13 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 Validate JWT Claims (exp, iss, aud) in Python

This code demonstrates how to decode and validate a JWT's essential claims—expiration (exp), issuer (iss), and audience (aud)—using the PyJWT library, returning clear error messages for common validation failures.

jwt authentication security
Python
import jwt
from datetime import datetime, timezone, timedelta

SECRET = "mock-secret"

def validate_token(token, expected_iss, expected_aud):
    try:
        decoded = jwt.decode(
            token,
            SECRET,
            algorithms=["HS256"],
            options={"require": ["exp", "iss", "aud"]},
         …
12 0 Open
API design & gRPC easy

How to Validate a JWT Signature in Python with a Mock Secret

Validates a JWT's signature using a mock secret, decoding and handling expired or invalid tokens gracefully.

jwt authentication security
Python
import jwt
import time

SECRET = "mock_secret_key_123"

def validate_token(token):
    try:
        payload = jwt.decode(token, SECRET, algorithms=["HS256"])
        return f"Valid token. Payload: {payload}"
    except jwt.ExpiredSignatureError:
        return "Token expired"
    except jwt.InvalidTokenError:
        …
12 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 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 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 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

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.