Difference between revisions of "Python Get Environment Variables"
Jump to navigation
Jump to search
| Line 1: | Line 1: | ||
https://able.bio/rhett/how-to-set-and-get-environment-variables-in-python--274rgt5 | https://able.bio/rhett/how-to-set-and-get-environment-variables-in-python--274rgt5 | ||
| + | # Making it harder | ||
``` | ``` | ||
| Line 17: | Line 18: | ||
BAR = os.environ.get('BAR') # None | BAR = os.environ.get('BAR') # None | ||
BAZ = os.environ['BAZ'] # KeyError: key does not exist. | BAZ = os.environ['BAZ'] # KeyError: key does not exist. | ||
| + | ``` | ||
| + | |||
| + | # Make it easy with decouple | ||
| + | |||
| + | .env | ||
| + | ``` | ||
| + | USER=foo | ||
| + | KEY=bar | ||
``` | ``` | ||
Revision as of 19:25, 11 March 2021
https://able.bio/rhett/how-to-set-and-get-environment-variables-in-python--274rgt5
Making it harder
import os
# Set environment variables
os.environ['API_USER'] = 'username'
os.environ['API_PASSWORD'] = 'secret'
# Get environment variables
USER = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')
# Getting non-existent keys
FOO = os.getenv('FOO') # None
BAR = os.environ.get('BAR') # None
BAZ = os.environ['BAZ'] # KeyError: key does not exist.
Make it easy with decouple
.env
USER=foo KEY=bar
from decouple import config
API_USERNAME = config('USER')
API_KEY = config('KEY')