36
How do I read environment variables in Python and set default values if they do not exist?
Loading...
Q&A · Answered
How do I read environment variables in Python and set default values if they do not exist?
Accepted answer
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'
from dotenv import load_dotenv
# Load from .env file
load_dotenv()
# Now use os.getenv as usual
secret = os.getenv('SECRET_KEY')Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.