Django utility for loading environment variables from .env files
npx @tessl/cli install tessl/pypi-django-dotenv@1.4.0A Django utility that loads environment variables from .env files into Django applications. This library bridges the gap between foreman-style .env file management and Django's manage.py command system, enabling twelve-factor app methodology by loading configuration from environment files.
pip install django-dotenvfrom dotenv import read_dotenv, parse_dotenvOr:
import dotenvfrom dotenv import read_dotenv
# Load .env file automatically (finds .env in calling file's directory)
read_dotenv()
# Load specific .env file
read_dotenv('/path/to/.env')
# Override existing environment variables
read_dotenv(override=True)
# Parse .env content without modifying os.environ
from dotenv import parse_dotenv
with open('.env', 'r') as f:
env_vars = parse_dotenv(f.read())
print(env_vars) # {'KEY': 'value', ...}Loads environment variables from .env files into os.environ, with automatic file discovery and optional override behavior.
def read_dotenv(dotenv=None, override=False):
"""
Read a .env file into os.environ.
Parameters:
- dotenv (str, optional): Path to .env file. If None, automatically discovers
.env file relative to caller's directory using stack introspection
- override (bool, optional): If True, values in .env override existing
system environment variables. If False, only sets variables that don't
already exist. Default: False
Returns:
None (modifies os.environ in-place)
Side Effects:
- Modifies os.environ with key-value pairs from .env file
- Issues UserWarning if .env file doesn't exist
- Issues SyntaxWarning for malformed lines
"""Parses .env file content into a dictionary without modifying the system environment.
def parse_dotenv(content):
"""
Parse .env file content into a dictionary.
Parameters:
- content (str): String content of a .env file
Returns:
dict: Dictionary of key-value pairs parsed from the content
Features:
- Supports single and double quoted values
- Handles variable substitution (e.g., $VAR, ${VAR})
- Supports escaped characters in double-quoted strings
- Ignores comments (lines starting with #) and empty lines
- Supports export statements (export KEY=value)
- Expands variables from local environment first, then os.environ
"""__version__ = "1.4.2"The library supports a flexible .env file format:
# Comments are supported
KEY=value
QUOTED_VALUE="value with spaces"
SINGLE_QUOTED='single quoted value'
EMPTY_VALUE=
EXPORT_STYLE=export KEY=value
# Variable substitution
BASE_PATH=/app
LOG_PATH=$BASE_PATH/logs
CONFIG_PATH=${BASE_PATH}/config
# Escaped variables (literal $)
LITERAL_DOLLAR=\$not_expandedThe library issues warnings for common scenarios:
UserWarning if specified .env file doesn't existSyntaxWarning for lines that don't match expected format# settings.py
import os
from dotenv import read_dotenv
# Load .env file at project root
read_dotenv(os.path.join(os.path.dirname(__file__), '.env'))
# Now use environment variables
DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'
SECRET_KEY = os.getenv('SECRET_KEY')
DATABASE_URL = os.getenv('DATABASE_URL')# manage.py
import os
import sys
from dotenv import read_dotenv
if __name__ == '__main__':
# Load .env before Django setup
read_dotenv()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
# ... rest of manage.py# wsgi.py
import os
from dotenv import read_dotenv
from django.core.wsgi import get_wsgi_application
# Load environment variables
read_dotenv(os.path.join(os.path.dirname(__file__), '.env'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()