PYTHON

Securely Load and Manage Environment Variables in Python with python-dotenv

Learn to safely manage sensitive application configurations like API keys and database credentials using environment variables and the `python-dotenv` library in Python.

# .env file (should NOT be committed to version control)
# DATABASE_URL="postgresql://user:password@host:port/dbname"
# API_KEY="your_secret_api_key_12345"
# DEBUG_MODE="False"

# app.py
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Access environment variables
db_url = os.getenv('DATABASE_URL')
api_key = os.getenv('API_KEY')
debug_mode_str = os.getenv('DEBUG_MODE', 'False') # Provide a default

# Convert to appropriate types
debug_mode = debug_mode_str.lower() == 'true'

print(f"Database URL: {db_url if db_url else 'Not set'}")
print(f"API Key: {'*' * (len(api_key) - 4) + api_key[-4:] if api_key else 'Not set'} (last 4 chars shown)")
print(f"Debug Mode: {debug_mode}")

if not db_url or not api_key:
    print("Warning: Essential environment variables are missing!")
    # In a real application, you might exit or raise an error

# Example usage (don't hardcode secrets!)
# connect_to_database(db_url)
# make_api_request(api_key)
How it works: This Python snippet demonstrates the secure practice of managing sensitive application configurations using environment variables with the `python-dotenv` library. It shows how to load variables from a `.env` file (which should be excluded from version control) and access them using `os.getenv()`. This prevents hardcoding credentials directly in the source code, reducing the risk of accidental exposure in repositories and making deployment to different environments more secure and flexible.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs