Handling Passwords and Secret Keys using Environment Variables

aryanabsalan

Aryan Absalan

Posted on February 14, 2022

Handling Passwords and Secret Keys using Environment Variables

To save passwords and secret keys in environment variables on Windows, you will need to open Advance System Setting.

You can navigate to control panel > System and Security > System > Advanced system Settings.
Now in Advance System Setting click on Environment Variables.
Here we can add new user variables and new system variables. We will add user variable by clicking New under user variables.

In the new window you can add Variable name and Variable value and click ok.
Now, click Ok on Environment Variables window to save changes.

Access the environmental variables
To access these variables in our python script, we need to import the os module.
We can do that by using os.environ.get() method and passing the key we want to access.

If you are using .python-dotenv method you need to add a couple of lines at the start of your application.

from dotenv import load_dotenv
load_dotenv()

In case of Django project, you should add the above script at the top of wsgi.py and manage.py file.

from dotenv import load_dotenv #for python-dotenv method
load_dotenv() #for python-dotenv method

import os

user_name = os.environ.get('USER')
password = os.environ.get('password')

print(user_name, password)

###### output

username password

💖 💪 🙅 🚩
aryanabsalan
Aryan Absalan

Posted on February 14, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related