Python Friday #107: Working With .env Files in Python

As last week’s post showed, our application gets its own copy of the environment variables when we start it. Would it not be great if we could extend that specific copy to include sensitive configuration values like API keys? We can achieve this with a .env file and this post shows you how to do that.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

The .env file

Various programming languages support the configuration format of a .env file. It is a simple key value pair that can look like this:

In Python we can use the package python-dotenv to append the configuration values to the environment variables our application can access. We can install this package with this command:

 

Update your .gitignore file

The .env files are a good place to store your environment specific values like connection strings to your database. However, to keep those values a secret, we cannot commit them to our Git repository. Make sure that you have an entry like this one in your .gitignore file:

 

Load the .env into the environment variables

We need to import dotenv and then call the method load_dotenv() to load our .env configuration into the environment variables dictionary. After that we can access the values from the .env file the same way we access all other environment variables:

Before the call to load_dotenv() there is no environment variable DATABASE_URL and we only get None back. After the call we can access the value from the .env file:

None
sqlite:///mydb.sqlite

 

Conclusion

The .env file is a great place to store application and environment specific configuration values. We must protect the file from an accidental commit, but one entry to .gitignore is enough to take care of that. I can recommend this approach and hope it will simplify your Python code as well.

4 thoughts on “Python Friday #107: Working With .env Files in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.