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 redact secrets from log messages in Python
This code defines a logging.Filter subclass that automatically redacts sensitive keys like password, token, and API key from any dict logged.
import logging
from dataclasses import dataclass
@dataclass
class ApiResponse:
status: int
body: dict
class SecretRedactor(logging.Filter):
SENSITIVE_KEYS = {"password", "token", "secret", "api_key"}
def filter(self, record: logging.LogRecord) -> bool:
if isinstance(record.msg, dict):
…
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.