Skip to content

Introduction to Python Dotenv Package

The python-dotenv package is a library that allows you to store sensitive data such as API keys, database credentials, and other environment-specific settings in a .env file. This file is not committed to version control, ensuring that your sensitive data remains secure.

Why Use Dotenv?

  • Keeps sensitive data separate from code
  • Easy to switch between development, testing, and production environments
  • Reduces the risk of exposing sensitive data in version control

Installation

To install the python-dotenv package, run the following command:

pip install python-dotenv

Basic Usage

Here's an example of how to use python-dotenv:

Step 1: Create a .env File

Create a new file named .env in the root of your project directory:

DB_HOST=localhost
DB_PORT=5432
DB_USER=myuser
DB_PASSWORD=mypassword

Step 2: Load Environment Variables

In your Python script, load the environment variables from the .env file using the load_dotenv function:

import os
from dotenv import load_dotenv

load_dotenv()  # loads variables from .env file

db_host = os.getenv('DB_HOST')
db_port = os.getenv('DB_PORT')
db_user = os.getenv('DB_USER')
db_password = os.getenv('DB_PASSWORD')

print(f"DB Host: {db_host}")
print(f"DB Port: {db_port}")
print(f"DB User: {db_user}")
print(f"DB Password: {db_password}")

Example Use Case: Database Connection

Here's an example of using python-dotenv to connect to a PostgreSQL database:

import os
import psycopg2
from dotenv import load_dotenv

load_dotenv()

db_host = os.getenv('DB_HOST')
db_port = os.getenv('DB_PORT')
db_user = os.getenv('DB_USER')
db_password = os.getenv('DB_PASSWORD')
db_name = os.getenv('DB_NAME')

try:
    conn = psycopg2.connect(
        host=db_host,
        port=db_port,
        user=db_user,
        password=db_password,
        database=db_name
    )
    print("Connected to database!")
except psycopg2.Error as e:
    print(f"Error connecting to database: {e}")

In this example, the database connection settings are stored in the .env file, and the python-dotenv package is used to load these settings into the Python script.

Best Practices

  • Keep your .env file out of version control by adding it to your .gitignore file.
  • Use meaningful variable names in your .env file.
  • Keep your .env file organized by grouping related variables together.

By following these best practices and using the python-dotenv package, you can keep your sensitive data secure and make it easy to switch between different environments.