DEV Community

loading...

Handling Secrets in Django.

VivekAsCoder
403 Bio is forbidden.
・1 min read

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!!'
Enter fullscreen mode Exit fullscreen mode

Post Step

  • Then
echo 'set -a; source .env; set +a' >> ./env/bin/activate
Enter fullscreen mode Exit fullscreen mode
  • 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')
Enter fullscreen mode Exit fullscreen mode

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!!'
Enter fullscreen mode Exit fullscreen mode

Post Step

  • Then install python-dotenv package using pip 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'))
...

Enter fullscreen mode Exit fullscreen mode
  • Now, you can use the os.getenv('NAME_HERE') to access the variables inside python.

  • @vivekascoder

Discussion (1)

Collapse
imdeepmehta profile image
Deep Mehta

Amazing man, ❤️
Glad to find your post