Reference library

Python Code Samples

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

40 matches
Errors & debugging medium

Redact secrets from log message formatter in Python

Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.

logging redaction security
Python
import re
import logging

class RedactingFormatter(logging.Formatter):
    """Formatter that masks sensitive data in log messages."""
    
    SENSITIVE_PATTERNS = [
        (re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
        (re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
14 0 Open
Files & data medium

Build a Secure Local Password Vault with Encrypted Storage in Python

A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.

encryption security passwords
Python
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass

class PasswordVault:
    def __init__(self, vault_file="vault.json", key_file="vault.key"):
        self.vault_file = vault_file
        self.key_file = key_file
        self.key = self._load_or_creat…
48 0 Open
Files & data medium

Encrypt and Decrypt Files Using Python

Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.

encryption decryption fernet
Python
import os
from pathlib import Path
from cryptography.fernet import Fernet

def generate_key(key_file: Path) -> bytes:
    key = Fernet.generate_key()
    key_file.write_bytes(key)
    return key

def load_key(key_file: Path) -> bytes:
    return key_file.read_bytes()

def encrypt_file(input_path: Path, key: bytes, out…
57 0 Open
Files & data medium

How to Load Pickle Files Safely in Python

This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.

pickle security serialization
Python
import pickle

# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
    def __reduce__(self):
        return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))

# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())

# Safe ap…
14 0 Open
Algorithms & data structures medium

How to Detect Hardcoded Secrets in Python Source Code

A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.

secrets regex security
Python
import re

def detect_secrets(text):
    """Detect potential hardcoded secrets in source code."""
    patterns = {
        'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
        'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
        'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
42 0 Open
AI & LLM integration patterns medium

How to Detect Prompt Injection in Python

Implements a regex-based heuristic in Python to flag common prompt injection attempts before sending input to an LLM.

prompt-injection regex llm-security
Python
import re

def contains_prompt_injection(user_input: str) -> bool:
    # Directives to ignore previous instructions or act as system
    ignore_patterns = [
        r"\bignore\s+(all\s+)?previous\s+instructions\b",
        r"\bdisregard\s+(all\s+)?previous\s+instructions\b",
        r"\bdon'?t\s+follow\s+(any\s+)?inst…
13 0 Open
Automation & scripting medium

Find Sensitive Information in Log Files with Python

Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.

regex security log-analysis
Python
import re
import os
from pathlib import Path

def find_sensitive_info(log_path):
    """Scans log files for patterns like emails, IPs, API keys, and passwords."""
    patterns = {
        'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
        'API Key'…
36 0 Open
Automation & scripting medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
35 0 Open
Automation & scripting medium

How to Detect Recently Installed Software in Python

Uses subprocess to call pip and parse package metadata to list recently installed Python packages.

pip subprocess automation
Python
import subprocess
import sys
from datetime import datetime, timedelta

def detect_recently_installed(days=7):
    """Detect recently installed software packages."""
    recent_packages = []
    cutoff_date = datetime.now() - timedelta(days=days)
    
    try:
        # For pip-installed packages (Python packages)
    …
33 0 Open
Automation & scripting medium

How to Scan Configuration Files for Security Issues in Python

Automatically scan configuration files for common security mistakes using regex rules in Python.

security config regex
Python
import re
import os
from pathlib import Path

SECURITY_RULES = [
    (r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
    (r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
    (r'debug\s*=\s*True', 'Debug mode enabled'),
    (r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
48 0 Open
Automation & scripting medium

How to Scan Open Ports on a Host with Python

A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.

socket network port-scanning
Python
import socket

def scan_ports(host, start_port, end_port):
    open_ports = []
    for port in range(start_port, end_port + 1):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((host, port))
        if result == 0:
            open_ports.app…
41 0 Open
Git + Python medium

Python Script to Rotate a Leaked API Key

A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.

security secrets file-scanning
Python
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""

import re
from pathlib import Path


CHECKLIST = [
    "Identify all files containing the leaked key",
    "Generate a new key with sufficient entropy",
    "Update the secret storage/CI environment variables",
    "Replace the ol…
14 0 Open
Cloud + Python medium

How to Evaluate IAM Policy Allow vs Deny in Python

Evaluate an AWS-style IAM policy dict with explicit deny overriding allow and default deny.

iam aws policy-evaluation
Python
import json


def evaluate_policy(action, resource, policy):
    """Evaluate an IAM-like policy dict.
    Explicit deny wins over allow. Default is deny.
    """
    for statement in policy.get("Statement", []):
        effect = statement.get("Effect")
        actions = statement.get("Action", [])
        resources = …
14 0 Open
API design & gRPC medium

How to Mock OAuth2 Bearer Token Auth Middleware in Python

Create a simple OAuth2 bearer token authentication middleware that verifies signed tokens and enforces scope-based access control.

oauth2 security middleware
Python
import hmac
import time
import base64
import json
from functools import wraps

VALID_TOKENS = {"test_token_123": {"user": "alice", "scope": "read:posts"}}


def generate_token(username: str) -> str:
    payload = {"user": username, "iat": int(time.time())}
    encoded = base64.urlsafe_b64encode(json.dumps(payload).enc…
13 0 Open
API design & gRPC medium

Verify Webhook HMAC Signatures in Python

Create and verify HMAC-SHA256 signatures for webhook payloads using Python's hmac module, protecting against tampering.

webhooks hmac security
Python
import hashlib
import hmac
import json

SECRET = b"super-secret-webhook-key"

def create_signature(payload: bytes) -> str:
    return hmac.new(SECRET, payload, hashlib.sha256).hexdigest()

def verify_signature(payload: bytes, signature: str) -> bool:
    expected = create_signature(payload)
    return hmac.compare_dig…
12 0 Open
Microservices patterns medium

How to Handle mTLS Certificate Rotation in Python

Detect mTLS certificate file changes by tracking modification time and hot-reload the SSL context in a running service.

mtls ssl certificate-rotation
Python
import ssl
import tempfile
import datetime
from pathlib import Path


class MTLSContext:
    def __init__(self, cert_path, key_path, ca_path):
        self.cert_path = Path(cert_path)
        self.key_path = Path(key_path)
        self.ca_path = Path(ca_path)
        self.context = None
        self.last_loaded_mtime …
12 0 Open
Microservices patterns medium

How to Mock mTLS Between Services in Python

Simulate mutual TLS authentication between two services using Python's ssl module with self-signed certificates.

mtls ssl security
Python
import ssl
import socket
import threading
import tempfile
from pathlib import Path
import subprocess

def create_test_cert(cert_path: Path, key_path: Path, common_name: str = "localhost"):
    """Generate a self-signed certificate using openssl."""
    subprocess.run([
        "openssl", "req", "-x509", "-newkey", "rs…
15 0 Open
Microservices patterns medium

JWT Service-to-Service Authentication Mock in Python

Create and verify HS256 JWTs for service-to-service authentication without external libraries.

jwt authentication hmac
Python
import hashlib
import hmac
import base64
import json
import time


class JWTMock:
    """Minimal JWT service-to-service mock using HS256."""
    
    def __init__(self, secret):
        self.secret = secret.encode()
    
    @staticmethod
    def _b64url_encode(data):
        return base64.urlsafe_b64encode(data).rstr…
14 0 Open
Microservices patterns medium

Zero Trust Service Auth Mock in Python

A simple HMAC-based token issuance and validation mock that enforces zero trust between microservices.

microservices authentication hmac
Python
import hmac
import hashlib
import json
import time

class ZeroTrustAuth:
    def __init__(self, secret_key):
        self.secret_key = secret_key
        self.service_tokens = {}

    def issue_token(self, service_name, ttl=300):
        payload = {
            "service": service_name,
            "issued_at": int(tim…
10 0 Open
Auth & security at scale medium

ACME LetsEncrypt Mock Challenge Server in Python

A minimal HTTP server that serves key authorizations for ACME/Let's Encrypt DNS-01 or HTTP-01 challenges during testing and validation.

acme letsencrypt http-server
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

# In-memory store simulating the ACME challenge token -> key authorization pair
challenge_store = {
    "token_example": "token_example.key_authorization"
}

class AcmeChallengeHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Extra…
15 0 Open
Auth & security at scale medium

AES GCM encryption and decryption in Python

Encrypt and decrypt data with AES-256-GCM using the cryptography library, including nonce generation and authenticated roundtrip verification.

aes-gcm cryptography encryption
Python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def aes_gcm_demo():
    plaintext = b"confidential message"
    key = AESGCM.generate_key(bit_length=256)
    aesgcm = AESGCM(key)
    nonce = os.urandom(12)
    
    ciphertext = aesgcm.encrypt(nonce, plaintext, None)
    decrypted = aesgcm.dec…
18 0 Open
Auth & security at scale medium

ECDH key agreement in Python with cryptography

Simulate ECDH key exchange between Alice and Bob, derive a shared secret, and generate a symmetric key with HKDF using the cryptography library.

ecdh cryptography key-agreement
Python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

def ecdh_mock():
    # Alice generates her key pair
    alice_private = ec.generate_private_key(ec.SECP256R1())
    alice_public = alice_pr…
15 0 Open
Auth & security at scale medium

How to Create and Verify HMAC SHA256 API Signatures in Python

Generate and verify HMAC-SHA256 signatures for API requests using Python's hmac, hashlib, and base64 modules.

hmac sha256 authentication
Python
import hmac
import hashlib
import base64
import json
from datetime import datetime, timezone

def create_api_signature(secret_key: str, method: str, path: str, timestamp: str, body: dict = None) -> str:
    """Create HMAC-SHA256 signature for API request."""
    payload = {
        "method": method.upper(),
        "p…
14 0 Open
Auth & security at scale medium

How to Create and Verify an OpenID Connect ID Token in Python

Generate and validate a mock OpenID Connect ID token (JWT) with HS256 signing using only the Python standard library.

jwt oidc security
Python
import base64
import hashlib
import hmac
import json
import time
from typing import Optional


def b64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("utf-8")


def b64url_decode(data: str) -> bytes:
    padding = "=" * (-len(data) % 4)
    return base64.urlsafe_b64decode(…
14 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.