How to load values from a dotenv file.

Basic

This approach is more manual but does not rely on package.

Store values in a shell file.

  • .env
      FOO=bar
      BUZZ=123
    

Then set the values as export variables.

$ export $(< .env | xargs)

Run a script that uses the variables.

  • main.py
      import from os import environ
    
    
      class Config:
          """
          """
    
          FOO = environ.get('FOO')
          BUZZ = environ.get('BUZZ')
    

Using Dotenv package

How to load a dotenv file, then use the values in your Python application, without using the export command.

Install

Install python-dotenv. Use the -U flag if installing globally to restrict to your user, or omit if in a virtual environment (recommended).

$ pip install python-dotenv

Configure values

Create a .env file which follows Bash Shell syntax, with content such as:

  • .env
      # A comment that will be ignored.
      REDIS_ADDRESS=localhost:6379
      MEANING_OF_LIFE=42
      MULTILINE_VAR="hello\nworld"
    

Load

Load the file in Python.

  • settings.py
      from os import environ
    
      from dotenv import load_dotenv
    
    
      load_dotenv()
      # OR
      load_dotenv(verbose=True)
    
      # OR
      from pathlib import Path 
      env_path = Path('.') / '.env'
      load_dotenv(dotenv_path=env_path)
    
      SECRET_KEY = environ("EMAIL")
      DATABASE_PASSWORD = environ("DATABASE_PASSWORD")