PYTHON

Securely Manage Environment Variables for Sensitive Data in Python

Learn to safely store and load sensitive application configurations like API keys and database credentials using environment variables with python-dotenv.

import os
from dotenv import load_dotenv

# 1. Load environment variables from a .env file (if it exists)
# This should be at the very top of your application's entry point.
load_dotenv()

# 2. Accessing environment variables
# It's good practice to provide default values or check for existence

# Database credentials
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = os.getenv('DB_PORT', '5432')
DB_USER = os.getenv('DB_USER', 'myuser')
DB_PASSWORD = os.getenv('DB_PASSWORD') # This one should probably not have a default
DB_NAME = os.getenv('DB_NAME', 'mydatabase')

# API Keys
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')

# Application specific settings
DEBUG_MODE = os.getenv('DEBUG_MODE', 'False').lower() == 'true'
APP_SECRET_KEY = os.getenv('APP_SECRET_KEY')

# 3. Example of checking for critical variables
if DB_PASSWORD is None:
    print("Warning: DB_PASSWORD environment variable not set!")
    # In a real application, you might raise an error and exit.

if STRIPE_SECRET_KEY is None:
    print("Warning: STRIPE_SECRET_KEY environment variable not set!")

# 4. Using the variables
print(f"
--- Configuration --- ")
print(f"Database Host: {DB_HOST}")
print(f"Database User: {DB_USER}")
print(f"Database Name: {DB_NAME}")
print(f"Stripe Key: {STRIPE_SECRET_KEY[:4]}{'*' * (len(STRIPE_SECRET_KEY) - 4) if STRIPE_SECRET_KEY else 'N/A'}") # Masking part of the key
print(f"Debug Mode: {DEBUG_MODE}")

# Example .env file content (this file should NOT be committed to version control):
# DB_HOST=your_db_host
# DB_PORT=5432
# DB_USER=your_db_user
# DB_PASSWORD=your_super_secret_db_password
# DB_NAME=your_database
# STRIPE_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxx
# GOOGLE_API_KEY=AIzaSyBxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# DEBUG_MODE=True
# APP_SECRET_KEY=a_very_long_and_random_string_for_app_secret
How it works: Hardcoding sensitive information like API keys, database credentials, or secret keys directly into your source code is a major security risk, especially if the code is committed to version control. This Python snippet demonstrates how to securely manage such data using environment variables with the `python-dotenv` library. `load_dotenv()` reads key-value pairs from a `.env` file (which should be excluded from version control) and injects them into `os.environ`. This allows your application to access sensitive data via `os.getenv()` without it ever being part of the codebase. This practice ensures sensitive configurations are separated from code, making deployments more secure and flexible across different environments (development, staging, production).

Need help integrating this into your project?

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

Hire DigitalCodeLabs