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
If you're using Python 3 and your system requires pip3, use:
pip3 install python-dotenv
To verify the installation:
pip show python-dotenv
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
Step 2: Create a .env File
In the root directory of your project, create a file named:
.env
Add your environment variables:
API_KEY=your_api_key_here
DATABASE_URL=mysql://user:password@localhost/dbname
DEBUG=True
SECRET_KEY=my_secret_key
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)
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
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"
Your .env file:
SECRET_KEY=django-secret-key
DEBUG=True
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()
Step 6: Keep Your .env File Out of Git
Never commit your .env file to version control.
Add it to .gitignore:
.env
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
Access them in Python:
import os
host = os.getenv("DATABASE_HOST")
port = os.getenv("DATABASE_PORT")
Troubleshooting
1. ModuleNotFoundError
Error:
ModuleNotFoundError: No module named 'dotenv'
Solution:
pip install python-dotenv
Ensure you're installing it in the same virtual environment you're running your application from.
2. Variables Returning None
Check that:
- The
.envfile exists in the project root. -
load_dotenv()is called beforeos.getenv(). - Variable names match exactly.
Example:
load_dotenv()
api_key = os.getenv("API_KEY")
Best Practices
- Never commit
.envfiles to Git repositories. - Use meaningful variable names.
- Store all secrets in environment variables.
- Use separate
.envfiles for development, staging, and production. - 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}")
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)