Why do we need Python Decouple?

As we continue to build our Django web application, we will eventually come to a realization that there is a lot of sensitive information that is stored in our settings.py file. Upon realizing this, you will think, how can I keep everything separate and safe.

Enter - python-decouple.

Step 1:

To install python-decouple in your application, open up your terminal and type in the following command:

pip install python-decouple

Step 2:

Create a .env file in your repository’s root directory.

Step 3:

As a test, we will store some important data, such as debug and our secret key. So, simply copy + paste your debug and secret key from settings.py as-is into your .env file.

# settings.py

DEBUG=False
SECRET_KEY='my_secret_key'

Step 4:

If you happen to be using Git be sure to .gitignore your .env file for security purposes.

Step 5:

Next, we need to import the decouple library:

# settings.py

from decouple import config

Step 6:

Now we want to get our parameters.

Decouple will always return our data as a string. To solve this problem, we need to cast it to a bool if we are expecting a Boolean or to an int if we are expecting an integer. Go back to your settings.py and modify your existing debug and secret key values with the following:

# settings.py

DEBUG = config('DEBUG', cast=bool)SECRET_KEY = config('SECRET_KEY')