PYTHON

Securely Load Environment Variables in Python with Flask-DotEnv

Discover how to securely manage sensitive API keys and credentials in Python Flask applications by loading them from environment variables using Flask-DotEnv.

import os
from flask import Flask
from dotenv import load_dotenv

# Load environment variables from a .env file (if it exists)
# This should be called early in your application lifecycle
load_dotenv()

app = Flask(__name__)

# Accessing sensitive configuration from environment variables
# This keeps secrets out of your codebase and version control
SECRET_KEY = os.getenv("FLASK_SECRET_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")
API_KEY = os.getenv("THIRD_PARTY_API_KEY")

if not SECRET_KEY:
    print("WARNING: FLASK_SECRET_KEY not set! Using a default (INSECURE FOR PRODUCTION).")
    SECRET_KEY = "super_secret_dev_key" # DO NOT USE IN PRODUCTION

# Example route using a secret
@app.route('/')
def index():
    return f"Welcome! Your API Key (first 5 chars): {API_KEY[:5]}..."

@app.route('/secret')
def secret_data():
    if SECRET_KEY == "super_secret_dev_key":
        return "Developer mode - real secret key not set!"
    return f"Secret key in use: {SECRET_KEY[:10]}..."

if __name__ == '__main__':
    # Create a dummy .env file for testing if it doesn't exist
    if not os.path.exists('.env'):
        with open('.env', 'w') as f:
            f.write("FLASK_SECRET_KEY=my_secure_flask_secret_key_12345
")
            f.write("DATABASE_URL=postgresql://user:pass@host:port/db
")
            f.write("THIRD_PARTY_API_KEY=my_very_secure_api_key_for_external_service
")
        print("Created a dummy .env file for demonstration.")
        print("Please restart the script or manually load .env variables.")

    app.run(debug=True)
How it works: This Python snippet for a Flask application demonstrates the secure practice of loading sensitive configuration data from environment variables using the `python-dotenv` library. Instead of hardcoding API keys, database credentials, or secret keys directly into the code (which risks exposure in version control), these values are stored in a `.env` file (which is typically excluded from Git) or set directly in the deployment environment. `load_dotenv()` then makes these variables accessible via `os.getenv()`, enhancing security by separating sensitive data from the application's source code.

Need help integrating this into your project?

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

Hire DigitalCodeLabs