Introduction
Managing configuration through environment variables for different environments.
Reading Variables
import os
# Basic reading
db_host = os.getenv("DB_HOST", "localhost")
db_port = os.getenv("DB_PORT", "5432")
# With type conversion
timeout = int(os.getenv("TIMEOUT", "30"))
# Required variables
api_key = os.environ["API_KEY"] # Raises KeyError if missing
dotenv
# pip install python-dotenv
from dotenv import load_dotenv
load_dotenv() # Load .env file
# Now os.getenv works with .env values
api_key = os.getenv("API_KEY")
.env File Format
DATABASE_URL=postgres://user:pass@localhost/db
API_KEY=abc123xyz
DEBUG=true
LOG_LEVEL=INFO
Practice Problems
- Load config from environment
- Create .env template
- Validate required variables
- Support multiple environments
- Use pydantic-settings for config