⚙️ Junior Python Track 37 • Environment & Secrets Management

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.

📄

.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.
⚙️ Environment Configuration & Secrets Studio

.env, Dev/Test/Prod Configs & Secrets Security

python-dotenv | Secrets | BaseSettings

📄 .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.

✅ Ready for Environment Execution
=== 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
# ==============================================================================
# ENVIRONMENT VARIABLE RETRIEVAL WITH FALLBACK & TYPE PARSING
# ==============================================================================
import os

def get_env_var(key: str, default: str = "", required: bool = False) -> str:
    val = os.environ.get(key, default)
    if required and not val:
        raise KeyError(f"Required env var '{key}' is missing!")
    return val
💎 Junior Track 37 Master Reference

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

⭐ Rate Track 37: Environment Configuration (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 36. Packaging & Distribution 🎓 Junior Hub (37 Modules Complete!) ⭐ Practice 100+ Interview Questions →