How to load a environment variables in python.

Felipe Gonzalez
2 min readJun 8, 2021

It is common to see that in our python programs we are going to need certain credentials, either to enter a database, to use a service or validate certain information, but it is not advisable to write the credentials verbatim in our code, since anyone who has Access our code, you will be able to read and know our license and that would be a huge security flaw that, depending on the area in which we are working, can have big consequences.

For that we have the environment variables, these variables are written in a separate document “.env” which will remain hidden from view and when we have to expose our code to other people, our credentials will not be seen, for this purpose we will use the python library “dotenv”, you can installed by typing on your terminal.

pip3 install python-dotenv

First of all you need to create a .env file and write your credentials.

HOST = the_host
PORT = 0000
USERNAME = your_username
DATABASE = some_database_name
PASSWORD = some_123_password

And in our python code.

# Import libraries we need 
import os
from dotenv import load_dotenv
# load the environment
load_dotenv()
# Load the environment variables
HOST = os.getenv('HOST')
PORT = os.getenv('PORT')
USERNAME = os.getenv('USERNAME')
DATABASE = os.getenv('DATABASE')
PASSWORD = os.getenv('PASSWORD')

Now we have our environment variables loaded in our python code and are ready to be used.

You can read more about it on: https://pypi.org/project/python-dotenv/

--

--

Felipe Gonzalez

Python BackEnd Developer, Machine Learning Python and AWS (Amazon Web Service)