Auth & security at scale
OAuth2, JWT, IAM patterns, secrets rotation, and least-privilege service auth.
How to Mock Environment Variables in Python for 12-Factor Config
Read 12-factor config from env vars and test/mock them with unittest.mock.patch.dict without touching the real environment.
import os
import json
from unittest.mock import patch
def load_config(env_prefix="APP"):
"""Read 12-factor style config from env vars"""
required = ["DATABASE_URL", "API_KEY"]
optional = {"PORT": "8080", "DEBUG": "false"}
config = {}
for key in required:
full_key = f"{env_prefix}_{key…
How to Mock HTTP Responses to Verify HSTS Headers in Python
This code demonstrates how to use unittest.mock to intercept and capture HTTP response headers, specifically the Strict-Transport-Security header, from a mocked HTTPServer handler for security validation.
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest.mock import patch
class StrictTransportMock(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
self.end_headers()
…
Browse by section
Each section groups closely related Python snippets.
Auth & security at scale — Python code examples
What you will find here
This page collects auth & security at scale snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.