Securely Loading Environment Variables in Python Using python-dotenv


Loading environment variables in Python code is a common task that developers need to perform when building applications that require sensitive information such as API keys or database credentials. In this blog post, we will explore how to load environment variables using the python-dotenv package.

The first step is to install the python-dotenv package. This can be done by running the following command in your terminal:

pip install python-dotenv

Once the package is installed, we can create a .env file in the root directory of our project and store our sensitive information inside. For example, let’s say we have an OpenAI API key that we want to access in our Python code. We can add the following line to our .env file:

OPENAI_API_KEY="2d9gggggggggggas"

To use this API key in our Python code, we need to load the environment variables from the .env file. This can be done using the load_dotenv() function from the dotenv module. Here’s an example code snippet:

import os
from dotenv import load_dotenv

load_dotenv()

OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

In this code snippet, we first import the os and dotenv modules. We then call the load_dotenv() function, which loads the environment variables from the .env file. Finally, we use the os.getenv() function to retrieve the value of the OPENAI_API_KEY variable from the environment.

One important reason to access sensitive information, such as an API key, using environment variables is to ensure security. By storing the sensitive information in an environment variable and loading it from a .env file, we can prevent the information from being hard-coded into our code and exposed in the event of a security breach.

It is also crucial to make sure that the .env file is not pushed to GitHub or other public repositories. To achieve this, we can add the .env file to our .gitignore file. The .gitignore file specifies which files or directories Git should ignore when committing changes. This way, the .env file is kept private and safe.
How to add .gitignore file can be see here

In conclusion, loading environment variables in Python code is an essential step when building applications that require sensitive information such as API keys or database credentials. Using the python-dotenv package and loading the environment variables from a .env file helps to ensure security and prevent sensitive information from being exposed. Remember to always keep the .env file private and not push it to public repositories.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC