Dotenv and Protecting Sensitive Information - ielts-ops/.github GitHub Wiki

Installing and Using python-dotenv with Python

What is dotenv?

python-dotenv is a Python library that helps manage environment variables in your projects by loading them from a .env file. This is particularly useful for storing sensitive information like API keys and database passwords securely, without exposing them directly in your code.

In your local folder, your secret information would be stored in a file called .env (hence the name). This file is ignored by Git and not uploaded to Github, but locally your code can still access it. Anyone who clones your repository would need this information to run it locally.

Although this Github account and all the code contained within are private, it's good practice to separate sensitive information from your main code.

Installing python-dotenv with Conda

To install python-dotenv using Conda, run the following command in your terminal or Anaconda Command Line:

conda install conda-forge::python-dotenv

This will install python-dotenv from the Conda Forge channel.

Creating a .env file

In your local repostiory create a file called ".env". In this file, you can list your secret variables. The file may look something like this:

# Database Configuration
DB_PASSWORD=mypassword
DB_NAME=mydatabase

# API Keys
API_KEY=your_api_key
SECRET_KEY=your_secret_key

Importing dotenv and Variables into Your Code

Once python-dotenv is installed, you can use it in your Python script or application. Import the dotenv module at the beginning of your script and use the load_dotenv() function, and it will automatically load the variables from the .env file.

After loading the environment, you can access the variables using os.environ:

from dotenv import load_dotenv
import os

# Load variables from .env into the environment
load_dotenv()

# Accessing variables
api_key = os.environ.get("API_KEY")
database_password = os.environ.get("DB_PASSWORD")

Replace "API_KEY" and "DB_PASSWORD" with the actual names of your variables.

Listing .env in .gitignore

For security reasons, it's crucial to exclude the .env file from version control. This ensures that sensitive information is not exposed to others. Create or update your .gitignore file to include the .env file:

# .gitignore
.env

This prevents the .env file from being tracked by Git and uploaded to repositories. This promotes a secure and organized approach to handling sensitive information in your code.