Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
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.
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…
How to Create a Mock Docker Registry Auth Token Server in Python
Build a mock Docker Registry token authentication server that issues signed JWT-like tokens for push and pull access using Python's standard library.
import base64
import hashlib
import hmac
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
class TokenAuthHandler(BaseHTTPRequestHandler):
"""Mock Docker Registry token authentication server."""
SECRET_KEY = b"mock-secret-key"
def generate_token(self, username: str, pas…
How to Build Cursor Pagination with Next and Prev Tokens in Python
A minimal cursor pagination implementation that returns next and previous cursor tokens for navigating a dataset.
from pprint import pprint
def make_cursor(page):
return f"page:{page:04d}"
def parse_cursor(cursor):
_, page = cursor.split(":", 1)
return int(page)
def paginate(all_items, page_size, cursor=None):
start = parse_cursor(cursor) if cursor else 0
end = start + page_size
items = all_items[sta…
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.
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…
Simulate a GIN Index for JSONB in Python
Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.
import json
import random
from collections import defaultdict
# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
def __init__(self):
self.posting_lists = defaultdict(list) # token -> list of doc_ids
def index(self, doc_id, json_obj):
"""Index a JSON documen…
How to Implement Refresh Token Rotation in Python
A mock auth service that issues, rotates, and validates refresh tokens, revoking old tokens on reuse to prevent replay attacks.
import time
import hashlib
import secrets
from typing import Dict, Optional, Tuple
class MockTokenService:
"""Simulates refresh token rotation for a simple auth system."""
def __init__(self):
# Token hash -> (user_id, rotation_count, expires_at)
self._active_tokens: Dict[str, Tuple[str, int,…
How to Implement a CSRF Token Double Submit Mock in Python
A mock CSRF protection class that generates and validates double-submit tokens using HMAC-SHA256 with a secret key.
import hmac
import hashlib
import secrets
class CSRFProtection:
def __init__(self, secret_key: str):
self.secret_key = secret_key.encode("utf-8")
def generate_token(self) -> str:
random_value = secrets.token_hex(16)
signature = hmac.new(
self.secret_key, random_value.enco…
OAuth2 authorization code flow mock in Python
A minimal HTTP server that mocks the OAuth2 authorization code flow, issuing codes via /authorize and exchanging them for tokens at /token.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
AUTH_CODE_STORE = {}
CLIENT_ID = "demo-client"
REDIRECT_URI = "http://localhost:8000/callback"
class OAuthHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
…
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.