Overview

A web application whether small or large will be having a lot of app secrets such as SECRET_KEY, api keys of different services used, database credentials etc.

The convenient way for anyone to use these is to hardcode them in source code.

It works, but it is also the most insecure way. We often push the code to repositories for version management or we share it among others resulting in exposing the app secrets.

The easiest and secure way is to use these secrets as environment variable and import them directly in app. Python decouple manages this for you. It also helps in managing application configurations and secrets based on the development environments

(DEVELOPMENT/PRODUCTION/STAGING ).

Decouple was originally designed for Django, but currently exist as an independent tool for separating setting from code.

Why to use this?

Web framework’s settings stores many different kinds of parameters:

  • Locale and i18n;
  • Middlewares and Installed Apps;
  • Resource handles to the database, Memcached, and other backing services;
  • Credentials to external services such as Amazon S3 or Twitter;
  • Per-deploy values such as the canonical hostname for the instance.

Why not just use environment variables?

Envvars works, but since os.environ only returns strings, it’s tricky.

Let’s say you have an envvar DEBUG=False. If you run:

if os.environ['DEBUG']:
    print True
else:
    print False

It will print True, because os.environ['DEBUG'] returns the string "False". Since it’s a non-empty string, it will be evaluated as True.

Decouple provides a solution that doesn’t look like a workaround: config('DEBUG', cast=bool).

Usage

Install:

pip install python-decouple

Step 1: Create a .env file at the root level of your project 

project
--- project
------ settings.py
------ urls.py
------ wsgi.py
--- .env

Now, set your own secret variable inside .env file like this:

DEBUG=True
SECRET_KEY=ARANDOMSECRETKEY
DB_HOST=HOSTNAME
DB_PASSWORD=PASSWORD

Now, in your settings.py, use the above variables like this:

from decouple import config


# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
	    'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT':''
    }
}

 

That's it for setting up a basic configuration, if you want know more have a look at the official doc:

https://pypi.org/project/python-decouple/

 

NOTE

  • It's a good idea to use version control like git, even for small projects. 
  • Add .env file to .gitignore, every user should have their own seperate .env file which should not be pushed alongwith your repository.