Using .env to securely store authentication keys in python

Chrispen Shumba
2 min readMay 16, 2021

This is a brief tutorial on how to store your secret keys in a.env file using the dotenv library rather than in your.bash profile or.zprofile.

I am opposed to storing your credentials in those files because it makes it difficult to work on multiple projects that require access to different databases/cloud accounts.

I have taken a leaf out of 4 ways to manage configuration in python.

  1. Create a new project folder and change directory into it.
# bash
mkdir project_name
cd project_name

2. Create our .env file. GITIGNORE THIS FILE!!!!

# bash
touch .env

This is a hidden file, you probably won’t see it in your folder structure. If in doubt you can always run cat .env to view the file contents or ls -a ./project_name to view the project_name folder contents.

3. populate our .env file. This can get a bit interesting. I am assuming you’re a bit comfortable with the command line. So just follow me,

# bash
vim .env

Don’t panic. It’s just vim.

  • press i to get into INSERT mode
  • copy and paste the below.
#.env
DATABASE_URL=postgres://username:password@localhost:5432/dbname
AWS_ACCESS_KEY=myaccesskey
AWS_SECRET_ACCESS_KEY=mysecretkey
OTHER_VARIABLE=zanawazhere
  • press escape.
  • Enter :wqto SAVE and QUIT.

Wasn’t too hard was it.

4. Create 2 folders such that our directory looks like.

project_name 
└── parent_folder
└── child_folder

5. Install dotenv using pip install dotenv.

6. Navigate to child_folder cd parent_folder/child_folder

7. Add the config.py.

# bash
vim config.py
  • Press i to get into INSERT mode
  • Copy and past the code below.
  • Enter :wqto SAVE and QUIT.

8. Execute config.py python config.py you should get the following output.

postgres://username:password@localhost:5432/dbname
zanawazhere

The point of me having the child and parent folder was to show that the dotenv package will crawl the directory to extract the secrets in .env.

Take it up a level

Now that we got the basics out of the way. Here is a bit of a realistic example.

  • Create a project_name folder. mkdir project_name
  • Create a utils folder in the project_name folder. mkdir utils
  • Create a config.py file in the utils folder.
  • Copy and paste the code below into the config.py file.

All we have done is create a config class which is inherited by the environment classes. The best thing is that we are not hard coding out environment keys in our code.

  • Create a main.py in the project_name folder. Copy and paste the below,

Run your main.py, you should see the output:

postgres://username:password@localhost:5432/dbname
zanawazhere
mysecretkey
myaccesskey

Take a moment to inhale. I believe you should be able to apply these concepts to your own personal projects.

I hope you got a good idea of what I was attempting to demonstrate. I would appreciate any feedback.

--

--