[Python] [Django] Hiding Secret Keys using django-environ.

Mahesh Van
Oct 23, 2020

--

Hey there, welcome! In this article, I am going to explain how to hide secret keys. In case if you are wondering how to protect API keys and secret keys of the Django project when uploading scripts to GitHub. Read ahead…

The below code snippet is from Django settings.py script.

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#nwh+sn=i6k697d9vu'

Python has a django-environ library, Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application and officially supports Django 1.11, 2.2 and 3.0

Installation:

$ pip install django-environ

Add the below piece of code to the settings.py file.

from environ import Envenv = Env()# reading .env file
env.read_env()
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'MY_SCRET_KEY'

Create a .env file in the project, don’t forget to add .env in .gitignore file

MY_SCRET_KEY = '#nwh+sn=i6k697d9vu'

Strings from os.environ are loaded from a .env file and filled in os.environ with setdefault method, to avoid overwrite the real environment.

The above statement intends, adding key manually to environmental variables without creating the .env file.

Windows:

Now you can add all the SECRET information you need, in .env file and still access them all.

--

--

Mahesh Van
Mahesh Van

Written by Mahesh Van

Mortal anatomy. Immortal dreams.

No responses yet