How to work with environment variables in Python
Answered
36
How do I read environment variables in Python and set default values if they do not exist?
L
Asked by
linux_expert
Bronze
•
311 rep
1 Answer
7
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')
O
Platinum
•
593 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer