Django — How to Keep Secrets Safe Using python-dotenv

Django — How to Keep Secrets Safe Using python-dotenv


We frequently have certain secret keys, OAuth keys, and other crucial information when working on a Django project that needs to be kept safe and private. Such keys should never be made public because doing so leaves your system open to security threats.

Today, we’ll look at how to use Python-Dotenv to conceal this kind of information. In essence, python-dotenv reads key-value pairs from an.env file and sets them as environment variables to be retrieved later, as we can see from the documentation.

Install this module first, of course.

pip install python-dotenv

then make a .env file in the project’s root directory. All the environment variable key-value pairs that our program needs will be placed here.

What should we put in the.env file, then?

  • The secret key that comes with every Django project — This needs to be kept private because it’s a crucial part of security in Django.

  • Social auth configs for Google

  • payment auth configs for Stripe or any other OAuth keys.

SECRET_KEY = 'YOUR SECRET KEY'

STRIPE_KEY = 'YOUR STRIPE KEY'
STRIPE_SECRET = 'YOUR STRIPE SECRET KEY'

GOOGLE_KEY = 'YOUR GOOGLE KEY'
GOOGLE_SECRET = 'YOUR GOOGLE SECRET KEY'

Load these configurations from.env into the settings.

from dotenv import load_dotenv
load_dotenv()  # loads the configs from .env

Now let’s retrieve our secret keys and OAuth keys using their key names rather than exposing them in the settings.

#settings.py

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = str(os.getenv('SECRET_KEY'))

# configs for stripe
STRIPE_TEST_PUBLIC_KEY = str(os.getenv('STRIPE_KEY'))
STRIPE_TEST_SECRET_KEY = str(os.getenv('STRIPE_SECRET'))

# social auth configs for google
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = str(os.getenv('GOOGLE_KEY'))
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = str(os.getenv('GOOGLE_SECRET'))

That’s it, with these steps we are making our app more secure.

It is important to note that if you have an application deployed, in the settings file, the path of the dot env should be specified as follows:

import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)