VivekAsCoder
Posted on November 9, 2020
Handling Secrets in Django.
Method 1:
Pre Steps:
- Create a virtual enviroment.
- Create a file with name
.env
then add the secrets like.
export DB_PASSWORD='XYZABZ'
export SUPER_SECRET='OMG!!'
Post Step
- Then
echo 'set -a; source .env; set +a' >> ./env/bin/activate
This will append the line to activate file now everytime you activate the env you can access these secret variables.
Now, you can use the below code to access the variables inside python.
import os
os.getenv('NAME_HERE')
Method 2:
Pre Steps:
- Create a virtual enviroment.
- Create a file with name
.env
then add the secrets like.
export DB_PASSWORD='XYZABZ'
export SUPER_SECRET='OMG!!'
Post Step
- Then install
python-dotenv
package usingpip install python-dotenv
. - Open
wsgi.py
and add these lines.
...
from dotenv import load_dotenv
from django.conf import settings
:
:
load_dotenv(os.path.join(settings.BASE_DIR, '.env'))
...
Now, you can use the
os.getenv('NAME_HERE')
to access the variables inside python.
💖 💪 🙅 🚩
VivekAsCoder
Posted on November 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.