0
# Django Dotenv
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: django-dotenv
7
- **Package Type**: PyPI
8
- **Language**: Python
9
- **Installation**: `pip install django-dotenv`
10
11
## Core Imports
12
13
```python
14
from dotenv import read_dotenv, parse_dotenv
15
```
16
17
Or:
18
19
```python
20
import dotenv
21
```
22
23
## Basic Usage
24
25
```python
26
from dotenv import read_dotenv
27
28
# Load .env file automatically (finds .env in calling file's directory)
29
read_dotenv()
30
31
# Load specific .env file
32
read_dotenv('/path/to/.env')
33
34
# Override existing environment variables
35
read_dotenv(override=True)
36
37
# Parse .env content without modifying os.environ
38
from dotenv import parse_dotenv
39
with open('.env', 'r') as f:
40
env_vars = parse_dotenv(f.read())
41
print(env_vars) # {'KEY': 'value', ...}
42
```
43
44
## Capabilities
45
46
### Environment File Loading
47
48
Loads environment variables from `.env` files into `os.environ`, with automatic file discovery and optional override behavior.
49
50
```python { .api }
51
def read_dotenv(dotenv=None, override=False):
52
"""
53
Read a .env file into os.environ.
54
55
Parameters:
56
- dotenv (str, optional): Path to .env file. If None, automatically discovers
57
.env file relative to caller's directory using stack introspection
58
- override (bool, optional): If True, values in .env override existing
59
system environment variables. If False, only sets variables that don't
60
already exist. Default: False
61
62
Returns:
63
None (modifies os.environ in-place)
64
65
Side Effects:
66
- Modifies os.environ with key-value pairs from .env file
67
- Issues UserWarning if .env file doesn't exist
68
- Issues SyntaxWarning for malformed lines
69
"""
70
```
71
72
### Environment File Parsing
73
74
Parses `.env` file content into a dictionary without modifying the system environment.
75
76
```python { .api }
77
def parse_dotenv(content):
78
"""
79
Parse .env file content into a dictionary.
80
81
Parameters:
82
- content (str): String content of a .env file
83
84
Returns:
85
dict: Dictionary of key-value pairs parsed from the content
86
87
Features:
88
- Supports single and double quoted values
89
- Handles variable substitution (e.g., $VAR, ${VAR})
90
- Supports escaped characters in double-quoted strings
91
- Ignores comments (lines starting with #) and empty lines
92
- Supports export statements (export KEY=value)
93
- Expands variables from local environment first, then os.environ
94
"""
95
```
96
97
### Package Version
98
99
```python { .api }
100
__version__ = "1.4.2"
101
```
102
103
## .env File Format
104
105
The library supports a flexible `.env` file format:
106
107
```bash
108
# Comments are supported
109
KEY=value
110
QUOTED_VALUE="value with spaces"
111
SINGLE_QUOTED='single quoted value'
112
EMPTY_VALUE=
113
EXPORT_STYLE=export KEY=value
114
115
# Variable substitution
116
BASE_PATH=/app
117
LOG_PATH=$BASE_PATH/logs
118
CONFIG_PATH=${BASE_PATH}/config
119
120
# Escaped variables (literal $)
121
LITERAL_DOLLAR=\$not_expanded
122
```
123
124
## Error Handling
125
126
The library issues warnings for common scenarios:
127
128
- **Missing .env file**: Issues `UserWarning` if specified .env file doesn't exist
129
- **Malformed lines**: Issues `SyntaxWarning` for lines that don't match expected format
130
- **Variable expansion**: Undefined variables expand to empty strings without errors
131
132
## Integration Patterns
133
134
### Django Settings
135
136
```python
137
# settings.py
138
import os
139
from dotenv import read_dotenv
140
141
# Load .env file at project root
142
read_dotenv(os.path.join(os.path.dirname(__file__), '.env'))
143
144
# Now use environment variables
145
DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'
146
SECRET_KEY = os.getenv('SECRET_KEY')
147
DATABASE_URL = os.getenv('DATABASE_URL')
148
```
149
150
### Django Management Commands
151
152
```python
153
# manage.py
154
import os
155
import sys
156
from dotenv import read_dotenv
157
158
if __name__ == '__main__':
159
# Load .env before Django setup
160
read_dotenv()
161
162
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
163
# ... rest of manage.py
164
```
165
166
### WSGI Applications
167
168
```python
169
# wsgi.py
170
import os
171
from dotenv import read_dotenv
172
from django.core.wsgi import get_wsgi_application
173
174
# Load environment variables
175
read_dotenv(os.path.join(os.path.dirname(__file__), '.env'))
176
177
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
178
application = get_wsgi_application()
179
```