DEV Community

VivekAsCoder
VivekAsCoder

Posted on

6 1

Handling Secrets in Django.

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (1)

Collapse
 
imdeepmehta profile image
Deep Mehta

Amazing man, ❤️
Glad to find your post

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay