37. Environment Configuration & Secrets
Master production environment configuration: manage .env files with python-dotenv, build class-based configuration hierarchies (DevelopmentConfig, TestingConfig, ProductionConfig), parse typed environment variables, redact sensitive credentials, and prevent secret leaks via .gitignore.
🎓 Junior Python Curriculum — Select Module
.env & Environment Variables
Store environment-specific configuration values outside your codebase in .env files loaded into os.environ using python-dotenv.
- `os.environ.get("KEY", default)`: Read with fallbacks.
- `load_dotenv()`: Automatically parse `.env` at startup.
- Strict validation: Raise KeyError on missing secrets.
Multi-Stage Config Classes
Use OOP inheritance (`BaseConfig` → `DevelopmentConfig`, `TestingConfig`, `ProductionConfig`) to handle environment variations cleanly.
- `DevelopmentConfig`: `DEBUG = True`, local database.
- `TestingConfig`: In-memory SQLite database (`:memory:`).
- `ProductionConfig`: Strict security, encrypted URI strings.
Secrets Security & Git Protection
Prevent credential leaks by masking passwords in logs, redacting database URIs, and enforcing `.env` exclusion in `.gitignore`.
- `.gitignore`: Ignore `.env`, `*.pem`, `secrets.json`.
- Secrets Redaction: Mask JWT keys in application logs.
- Pydantic BaseSettings: Type-safe settings validation.
.env, Dev/Test/Prod Configs & Secrets Security
📄 .env & Environment Variables
Keep credentials out of codebase using `.env` files loaded dynamically via `os.environ` and `python-dotenv`.
🎛️ Dev / Test / Prod Configs
Class-based hierarchy cleanly separating local dev settings, testing in-memory DBs, and production strict security.
🔒 Secrets & Git Protection
Mask secret keys in logs, redact passwords in DB connection URIs, and enforce strict `.gitignore` exclusion rules.
=== EXECUTION RESULT === --- Parsed .env Configuration --- APP_ENV = development API_PORT = 8080 SECRET_KEY = super-secret-production-jwt-key-2026 DATABASE_URL = postgresql://cloud_admin:SecurePass123!@localhost:5432/teachcloud_db ALLOWED_HOSTS = teachcloud.dev,api.teachcloud.dev DEBUG = true
37. Environment Configuration Strategy Matrix
📊 Configuration Management Approaches
| Approach | Mechanism | Security Level | Best Used For |
|---|---|---|---|
| Hardcoded Values | Direct code constants (`SECRET = "123"`) | ❌ UNSAFE (Leaks to Git) | Never in real projects |
| .env Files | Un-tracked local text file (`python-dotenv`) | ✅ HIGH (Local Dev / Staging) | Local development & staging instances |
| OS Environment Variables | OS process environment (`os.environ`) | ✅ HIGH (Docker / Kubernetes) | Containerized cloud deployments |
| Vault / Secrets Manager | AWS Secrets Manager, HashiCorp Vault | 🛡️ ENTERPRISE (Auto-Rotating) | Enterprise microservices & finance APIs |