2 minute read

Introduction

Here is a step-by-step guide to creating a Python application, including its environment variables. It is particularly useful when we need to keep sensitive information (for example API keys, data base passwords, etc.) secure and separately from the code. For instance, we develop applications whose source code is stored in git repositories. We do not wish to share some sensitive information contained in the source code.

A number of Python libraries are available that can assist with managing environment variables in Python. Here are some of them:

  • python-config,
  • environs,
  • dynaconf,
  • configobj,
  • decouple.

Let me share with you the most commonly used Python library, which is python-dotenv.

Installing the library

The first step is installing the library in our environment:

pip install python-dotenv

Creating .env file

The second step we need to do is to create a .env file in the root directory of the project. This will let us configure the environment variables. The .env file must be similar to the bash syntax. Here is an example of this file:

USER = 'mbartcus'
PASW = 'THIS_is_a_SECRET'
MAIL = ${USER}@gmail.com

Observe for example that here if we use a variable in a value, this variable is surrounded by { } brackets.

To push your code with git, make sure your .env file is added to the .gitignorefile.

Creating a python application

And finally, we can load our environment variable in the python application.

import os
from dotenv import load_dotenv # import the package

load_dotenv()  # take environment variables from .env.

usr=os.environ.get("USER")
psw=os.environ.get("PASW")
mail=os.environ.get("MAIL")

Another way to load the environment variables is by using the dotenv_values function. This function is very similar to the load_dotenvfunction. However, in this case, a dictionary of key:values is created. Now, given the code:

from dotenv import dotenv_values

config = dotenv_values(".env") # creates a dictionary

config would be

{'USER':'mbartcus', 'PASW':'THIS_is_a_SECRET', 'MAIL':'mbartcus@gmail.com'}

Example

For example, let us see the following source code:

from dotenv import load_dotenv
import os

class MyAPI:
    def __init__(self):
        load_dotenv()  # Load environment variables from .env file
        self.api_key = os.getenv("API_KEY")
        self.base_url = os.getenv("API_BASE_URL")

    def make_request(self, endpoint):
        # Use the API key and base URL to make a request
        url = self.base_url + endpoint
        headers = {"Authorization": f"Bearer {self.api_key}"}
        response = requests.get(url, headers=headers)
        return response.json()

This is an example of the MyAPI class that is initialized with the load_dotenv() function. This will load the variables from the .env file that is placed in the same folder as the MyAPI class. The MyAPI class also defines two instance variables api_key and base_url which takes values from the API_KEY and API_BASE_URL environment variables respectively. Recall that these two variables are defined in .env file.