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.
To install python-decouple in your application, open up your terminal and type in the following command:
pip install python-decouple
Create a .env file in your repository’s root directory.
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.
If you happen to be using Git be sure to .gitignore your .env file for security purposes.
Next, we need to import the decouple library:
from decouple import config
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:
DEBUG = config('DEBUG', cast=bool)SECRET_KEY = config('SECRET_KEY')