Skip to content

Q&A · Answered

How to work with environment variables in Python

asked 9 months, 1 week ago 1989 views 1 answer
36

How do I read environment variables in Python and set default values if they do not exist?

1 Answer

One accepted
7

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Reading environment variables

import os

# Get with default value
database_url = os.getenv('DATABASE_URL', 'sqlite:///db.sqlite3')

# Get (raises KeyError if not exists)
api_key = os.environ['API_KEY']

# Check if exists
if 'DEBUG' in os.environ:
    debug = os.environ['DEBUG'] == 'True'

Using python-dotenv

from dotenv import load_dotenv

# Load from .env file
load_dotenv()

# Now use os.getenv as usual
secret = os.getenv('SECRET_KEY')

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.