env variables python code example

Example 1: get environment variables python

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.

Example 2: python env

python3 -m venv tutorial-env
tutorial-env\Scripts\activate.bat (window)
source tutorial-env/bin/activate (linux)

Example 3: how to use information from env variables in python

from decouple import config

API_USERNAME = config('USER')
API_KEY = config('KEY')