Skip to content

Instantly share code, notes, and snippets.

@kadams54
Last active July 2, 2020 18:04
Show Gist options
  • Save kadams54/a80c7b31d3f1993a5051e5cc957dea73 to your computer and use it in GitHub Desktop.
Save kadams54/a80c7b31d3f1993a5051e5cc957dea73 to your computer and use it in GitHub Desktop.

Django-environ

Installing

pip install django-environ

OR

Edit your requirements.txt to add:

django-environ==0.4.5  # https://github.com/joke2k/django-environ

Then run pip install -r requirements.txt.

Documentation

https://django-environ.readthedocs.io/en/latest/

Usage

Place something like this in your config/settings/base.py file:

import environ

env = environ.Env()

# Reads a .env file; OS env vars take precendence over this file;
# note this assumes your .env file is in the same directory as
# the python file containing this code. You will probably need to
# do some path traversal with os.path,
# https://docs.python.org/3/library/os.path.html
# to get to the right place.
env.read_env(environ.Path(__file__).path(".env").root)

Once you've initialized the env as above, you can import it into other places in your application for use:

from foobar.config.settings.base import env

# To access a string ENV VAR
stress_testing_enabled = env('STRESS_TESTING_SHARED_SECRET')

# To access a typed (non-string) ENV VAR
stress_testing_eanbled = env.bool('STRESS_TESTING_ENABLED')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment