72. Security and .env
Before deploying our application, we will need to change several segments to add security to the site, specially in the settings.py file.
First, it is heavily recommended to create a .env file in the root of the project, where you will stode most API keys or other sensitive data.
Also, if the project is inside another subfolder that is NOT the repository root folder, move it out of there into the repository root folder (for instance when the project was inside the ecommerce_main folder that was inside the repository folder)

We will access those variables using the dotenv library
pip install python-dotenv
and on each file that will need to acess the enviromental variables, we will import the load_dotenv funcition from the library and call it like so:
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv('secret_key')
In this case we are acessing the SECRET_KEY variable from the .env file, we will follow this pattern for all environmental variables. Also, name all the enviromental variables in caps lock for good practice and DO NOT INCLUDE THE .ENV IN THE GIT COMMITS.
Important: At the start of the python file, before calling the variables from the .env file, call the load_dotenv function.
Last updated