← Back to all snippets
PYTHON

Securely Load Environment Variables with Python-dotenv

Prevent sensitive data exposure by loading environment variables from a .env file into your Python application. This snippet demonstrates safe configuration management.

import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Access environment variables
DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///./test.db')
API_KEY = os.getenv('API_KEY')
DEBUG_MODE = os.getenv('DEBUG_MODE', 'False').lower() == 'true'

def connect_to_database():
    # In a real application, use DATABASE_URL to connect
    print(f"Connecting to database using: {DATABASE_URL}")
    # Example: database_connection = create_engine(DATABASE_URL)
    pass

if __name__ == "__main__":
    print(f"API Key: {API_KEY if API_KEY else 'Not Set'}")
    print(f"Debug Mode: {DEBUG_MODE}")
    connect_to_database()

    if API_KEY is None:
        print("WARNING: API_KEY is not set. Please create a .env file with API_KEY=YOUR_SECRET_KEY")

# Example .env file content:
# DATABASE_URL="postgresql://user:password@host:port/dbname"
# API_KEY="your_super_secret_api_key_123"
# DEBUG_MODE="True"
How it works: This Python snippet uses the `python-dotenv` library to load environment variables from a `.env` file. This practice prevents sensitive information like database credentials or API keys from being hardcoded directly into the application's source code, enhancing security by separating configuration from code and keeping secrets out of version control.

Need help integrating this into your project?

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

Hire DigitalCodeLabs