================================================================================ GMAIL CLEANUP - CHALLENGE 1 SOLUTION Chapter 2: Configuration Management Challenge: Create config.py ================================================================================ PROBLEM: Build a Config class that: 1. Loads .env file from current directory 2. Reads GMAIL_USER, API_REQUEST_TIMEOUT, MAX_RESULTS 3. Uses defaults for timeout (10) and max_results (100) 4. Returns all values SOLUTION: ================================================================================ File: config.py import os from pathlib import Path from dotenv import load_dotenv # Load .env from same directory as this file ENV_FILE = Path(__file__).parent / ".env" load_dotenv(ENV_FILE) class Config: """Application configuration.""" def __init__(self): # Gmail settings self.gmail_user = os.environ.get('GMAIL_USER') # API settings with defaults self.api_timeout = int(os.environ.get('API_REQUEST_TIMEOUT', '10')) self.max_results = int(os.environ.get('MAX_RESULTS', '100')) # Cleanup settings with defaults self.days_old = int(os.environ.get('DELETE_OLDER_THAN_DAYS', '365')) self.min_attachment_mb = int(os.environ.get('MIN_ATTACHMENT_SIZE_MB', '10')) def __str__(self): return f""" Configuration: Gmail User: {self.gmail_user} API Timeout: {self.api_timeout}s Max Results: {self.max_results} Delete emails older than: {self.days_old} days Min attachment size: {self.min_attachment_mb}MB """ # Usage example if __name__ == "__main__": config = Config() print(config) HOW IT WORKS ================================================================================ 1. LOAD .ENV FILE ENV_FILE = Path(__file__).parent / ".env" load_dotenv(ENV_FILE) - Finds .env in same directory as config.py - Loads all variables into os.environ 2. READ VARIABLES self.gmail_user = os.environ.get('GMAIL_USER') - Gets GMAIL_USER from .env - Returns None if not found 3. USE DEFAULTS self.api_timeout = int(os.environ.get('API_REQUEST_TIMEOUT', '10')) - Gets API_REQUEST_TIMEOUT from .env - Default is 10 if not found - Converts to int automatically 4. RETURN OBJECT config = Config() print(config.gmail_user) - Easy to access values anywhere TESTING ================================================================================ python config.py Expected output: Configuration: Gmail User: emubantam@gmail.com API Timeout: 10s Max Results: 100 Delete emails older than: 365 days Min attachment size: 10MB KEY TAKEAWAYS ================================================================================ ✅ Path(__file__).parent finds script directory ✅ load_dotenv() loads environment variables ✅ os.environ.get() reads variables with defaults ✅ Config class centralizes all settings ✅ Easy to extend with more variables ================================================================================