PYTHON
Securely Loading Environment Variables
Learn to securely manage and load sensitive configuration details like API keys, database credentials, and secrets using environment variables with Python's `python-dotenv` library.
import os
from dotenv import load_dotenv
# 1. Create a .env file in the same directory as your Python script:
# .env content example:
# DATABASE_URL="postgresql://user:password@host:port/dbname"
# API_KEY="your_super_secret_api_key_123"
# DEBUG_MODE=True
# Load environment variables from .env file
# This should typically be one of the first lines of code executed
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 value
# Convert string value to boolean if necessary
debug_mode = debug_mode_str.lower() == 'true'
print(f"Database URL: {db_url}")
print(f"API Key: {'*' * (len(api_key) - 4) + api_key[-4:] if api_key else 'None'}") # Censor for display
print(f"Debug Mode: {debug_mode}")
# Example of using a non-existent variable (returns None)
non_existent = os.getenv("NON_EXISTENT_VAR")
print(f"Non-existent variable: {non_existent}")
# Best practice: Check if critical variables are loaded
if db_url is None:
print("WARNING: DATABASE_URL not set in environment!")
How it works: Hardcoding sensitive information like API keys, database credentials, or secret tokens directly into your codebase is a major security risk. This Python snippet demonstrates how to securely manage these secrets using environment variables and the `python-dotenv` library. By storing secrets in a `.env` file (which should be excluded from version control), `load_dotenv()` injects them into the application's environment. This practice keeps sensitive data out of your source code, allows for different configurations across environments (development, staging, production), and reduces the risk of accidental exposure.