DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

How to Install `python-dotenv` in Python

Environment variables are an essential part of modern software development. They allow developers to store sensitive information such as API keys, database credentials, and secret tokens outside the source code. In Python, one of the most popular libraries for managing environment variables is python-dotenv.

This article will guide you through installing and using python-dotenv in your Python projects.

What is python-dotenv?

python-dotenv is a Python package that reads key-value pairs from a .env file and loads them into environment variables. This helps keep sensitive configuration data separate from your codebase.

Benefits of Using python-dotenv

  • Keeps secrets out of source code
  • Simplifies configuration management
  • Makes applications easier to deploy across different environments
  • Works seamlessly with frameworks like Django, Flask, and FastAPI

Step 1: Install python-dotenv

Open your terminal or command prompt and run:

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

If you're using Python 3 and your system requires pip3, use:

pip3 install python-dotenv
Enter fullscreen mode Exit fullscreen mode

To verify the installation:

pip show python-dotenv
Enter fullscreen mode Exit fullscreen mode

You should see package information similar to:

Name: python-dotenv
Version: 1.x.x
Summary: Read key-value pairs from a .env file and set them as environment variables
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a .env File

In the root directory of your project, create a file named:

.env
Enter fullscreen mode Exit fullscreen mode

Add your environment variables:

API_KEY=your_api_key_here
DATABASE_URL=mysql://user:password@localhost/dbname
DEBUG=True
SECRET_KEY=my_secret_key
Enter fullscreen mode Exit fullscreen mode

Step 3: Load Environment Variables

Create a Python file and load the variables using load_dotenv().

from dotenv import load_dotenv
import os

# Load variables from .env file
load_dotenv()

api_key = os.getenv("API_KEY")
debug = os.getenv("DEBUG")

print(api_key)
print(debug)
Enter fullscreen mode Exit fullscreen mode

When you run the script, the values from the .env file will be loaded into your application.


Step 4: Using python-dotenv in Django

Install the package:

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

In your settings.py file:

from dotenv import load_dotenv
import os

load_dotenv()

SECRET_KEY = os.getenv("SECRET_KEY")
DEBUG = os.getenv("DEBUG") == "True"
Enter fullscreen mode Exit fullscreen mode

Your .env file:

SECRET_KEY=django-secret-key
DEBUG=True
Enter fullscreen mode Exit fullscreen mode

This prevents sensitive settings from being hardcoded into your project.


Step 5: Using python-dotenv in Flask

from dotenv import load_dotenv
import os
from flask import Flask

load_dotenv()

app = Flask(__name__)

app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")

@app.route("/")
def home():
    return "Hello World"

if __name__ == "__main__":
    app.run()
Enter fullscreen mode Exit fullscreen mode

Step 6: Keep Your .env File Out of Git

Never commit your .env file to version control.

Add it to .gitignore:

.env
Enter fullscreen mode Exit fullscreen mode

This ensures sensitive information remains private.


Common Environment Variables

Example .env file:

DATABASE_HOST=localhost
DATABASE_PORT=3306
DATABASE_NAME=mydb
DATABASE_USER=root
DATABASE_PASSWORD=password

OPENAI_API_KEY=your_openai_key
WHATSAPP_TOKEN=your_whatsapp_token

DEBUG=True
Enter fullscreen mode Exit fullscreen mode

Access them in Python:

import os

host = os.getenv("DATABASE_HOST")
port = os.getenv("DATABASE_PORT")
Enter fullscreen mode Exit fullscreen mode

Troubleshooting

1. ModuleNotFoundError

Error:

ModuleNotFoundError: No module named 'dotenv'
Enter fullscreen mode Exit fullscreen mode

Solution:

pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode

Ensure you're installing it in the same virtual environment you're running your application from.

2. Variables Returning None

Check that:

  • The .env file exists in the project root.
  • load_dotenv() is called before os.getenv().
  • Variable names match exactly.

Example:

load_dotenv()

api_key = os.getenv("API_KEY")
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Never commit .env files to Git repositories.
  2. Use meaningful variable names.
  3. Store all secrets in environment variables.
  4. Use separate .env files for development, staging, and production.
  5. Validate required environment variables when your application starts.

Example:

import os
from dotenv import load_dotenv

load_dotenv()

required_vars = ["API_KEY", "DATABASE_URL"]

for var in required_vars:
    if not os.getenv(var):
        raise ValueError(f"Missing environment variable: {var}")
Enter fullscreen mode Exit fullscreen mode

Conclusion

The python-dotenv package provides a simple and secure way to manage configuration settings in Python applications. By storing sensitive information in a .env file and loading it with load_dotenv(), you can keep your code clean, secure, and easy to maintain. Whether you're building a Django application, Flask API, FastAPI service, or automation script, python-dotenv is a valuable tool that every Python developer should know.

Top comments (0)