Python Environment Variables

Environment Variables are variables that stored outside of the program. Mostly used for security. In our program, secret key, database url and api key are the values that we don’t want to show public. Environment Variables are variables in our environment. Different Environment have different variables. Means that other users who download and run our program in their local computer, will not see those variables stored in our environment. If they want to use those key, they will need to set their testing variables to their environment variables. Environment variables are stored with keys and values and easy to set new variables and to use those values.

Environment Variables

Show all environment variables

in command line

> set 

in bash

$ env

Set new value in environment variables

in command

set SECRET_KEY=hello

in bash

$ export SECRET_KEY=helloenv

Python OS module

os.environ will show all variables in environment.

import osprint(os.environ)

set new value

os.environ['SECRET_KEY'] = "hello"

get env value

print(os.getenv('SECRET_KEY'))

dotenv python module

Now, we need to seperate env file to store env values for our program. So when we publish our program, we only need to hide env file in gitignore.

pip install python-dotenv

.env

SECRET_KEY=thisissecretkey

main.py

import os
from dotenv import load_dotenv
load_dotenv()

print(os.getenv('SECRET_KEY'))

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cho Zin Thet

Cho Zin Thet

Learning javascript and web-development