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'))

--

--

--

Learning javascript and web-development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Governance Period 2 Payouts

Career Planning

Run your application on multiple servers and rely on Nginx load balancer

CS373 Spring 2022: Tiago Grimaldi Rossi

CKS Exam Series #1 Create Cluster & Security Best Practices

Get started with Service Workers

ProvBook: Provenance of Jupyter Notebooks

Day 54: Longest Unique Sequence

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

More from Medium

How to install and setup Pycharm and venv in Windows 10

Namespaces in Python

Why is Python So Popular?

Python 101: Ultimate Python Guide or Introduction to Modern Python