Setting Up Environment Variables for Python Projects

I wanted to make sure I could use my API keys across multiple Python projects without having to specify them every time. Here’s how I set it up.

Step 1: Store API Keys in Environment Variables

1.1 Create a .env File

First, I created a .env file in my home directory (~/.env). This file holds all my API keys:

API_KEY_TWILIO=your_twilio_api_key
API_KEY_STRIPE=your_stripe_api_key
API_KEY_OPENAI=your_openai_api_key

Step 2: Access Environment Variables in Your Python Project

2.1 Install python-dotenv

To load the environment variables in my Python project, I installed the python-dotenv package:

pip install python-dotenv

2.2 Load the .env File in Python

In my Python script, I used python-dotenv to load the .env file and access the environment variables:

import os
from dotenv import load_dotenv

# Automatically load the .env file from the current directory or parent directories
load_dotenv()

# Access the API keys
twilio_api_key = os.getenv('API_KEY_TWILIO')
stripe_api_key = os.getenv('API_KEY_STRIPE')
openai_api_key = os.getenv('API_KEY_OPENAI')

print(f'Twilio API Key: {twilio_api_key}')
print(f'Stripe API Key: {stripe_api_key}')
print(f'OpenAI API Key: {openai_api_key}')

This setup helps me keep my API keys secure and easily accessible across all my Python projects. Easy and efficient!


Update to Quick Start Script

As a last step, I updated my quick start scriptstart_python_project.sh, to install python-dotenv and include a starter main.py file for handling environment variables. Here's the updated script on GitHub.

You can read more about it here, but here's the tl;dr:

I love experimenting with Python libraries and APIs, but setting up new projects can be a hassle. This script automates the setup so I can start coding quickly. Here's what it does:

  • Prompts for a project name.
  • Creates a new project directory.
  • Sets up a virtual environment.
  • Installs required dependencies.
  • Creates folders for source code, tests, and docs.
  • Generates main.pyrequirements.txt, and README.md.
  • Initializes a Git repo.
  • Opens main.py in VS Code.