0
# Framework Integration
1
2
Native integration with Flask and Django frameworks providing seamless configuration management for web applications with automatic settings binding and framework-specific optimizations. These integrations enable dynaconf to work naturally within existing web application architectures.
3
4
## Capabilities
5
6
### Flask Integration
7
8
Integrate dynaconf with Flask applications for automatic configuration management.
9
10
```python { .api }
11
class FlaskDynaconf:
12
"""Flask extension for dynaconf integration."""
13
def __init__(
14
self,
15
app=None, # Flask application instance
16
instance_relative_config=False, # Use instance-relative config
17
dynaconf_instance=None, # Existing dynaconf instance
18
extensions_list=False, # Enable extensions list
19
**kwargs # Additional dynaconf options
20
): ...
21
22
def init_app(self, app, **kwargs):
23
"""Initialize the extension with Flask app."""
24
...
25
26
def make_config(self, app):
27
"""Create configuration object for Flask app."""
28
...
29
30
class DynaconfConfig:
31
"""Configuration object that integrates dynaconf with Flask's config system."""
32
def __init__(self, _settings, _app, *args, **kwargs): ...
33
34
def get(self, key, default=None):
35
"""Get configuration value."""
36
...
37
38
def load_extensions(self, key="EXTENSIONS", app=None):
39
"""Load Flask extensions dynamically."""
40
...
41
42
# Standard dict methods
43
def keys(self): ...
44
def values(self): ...
45
def items(self): ...
46
def setdefault(self, key, default): ...
47
```
48
49
Usage examples:
50
51
```python
52
from flask import Flask
53
from dynaconf import FlaskDynaconf
54
55
# Method 1: Direct initialization
56
app = Flask(__name__)
57
FlaskDynaconf(app)
58
59
# Method 2: Factory pattern
60
app = Flask(__name__)
61
dynaconf = FlaskDynaconf()
62
dynaconf.init_app(app)
63
64
# Method 3: With custom settings
65
app = Flask(__name__)
66
FlaskDynaconf(
67
app,
68
envvar_prefix="MYAPP",
69
settings_files=["config.toml", "local.yaml"],
70
environments=True
71
)
72
73
# Access settings through Flask's config
74
@app.route("/")
75
def index():
76
debug_mode = app.config.DEBUG
77
database_url = app.config.DATABASE_URL
78
return f"Debug: {debug_mode}, DB: {database_url}"
79
```
80
81
### Django Integration
82
83
Integrate dynaconf with Django applications for dynamic settings management.
84
85
```python { .api }
86
def DjangoDynaconf(settings_module):
87
"""
88
Configure Django to use dynaconf for settings management.
89
90
Args:
91
settings_module (str): Django settings module name
92
93
Returns:
94
LazySettings: Configured dynaconf instance for Django
95
"""
96
...
97
```
98
99
Usage examples:
100
101
```python
102
# In Django settings.py
103
import dynaconf
104
105
# Replace Django's default settings with dynaconf
106
settings = dynaconf.DjangoDynaconf(__name__)
107
108
# The settings object works like Django's normal settings
109
DEBUG = settings.DEBUG
110
DATABASES = settings.DATABASES
111
SECRET_KEY = settings.SECRET_KEY
112
113
# Environment-based configuration
114
if settings.current_env == "production":
115
ALLOWED_HOSTS = settings.ALLOWED_HOSTS
116
else:
117
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
118
```
119
120
## Framework-Specific Patterns
121
122
### Flask Application Factory
123
124
Configure dynaconf in Flask application factories.
125
126
```python
127
from flask import Flask
128
from dynaconf import FlaskDynaconf
129
130
def create_app(config_name=None):
131
"""Application factory with dynaconf integration."""
132
app = Flask(__name__)
133
134
# Configure dynaconf with environment-specific settings
135
FlaskDynaconf(
136
app,
137
envvar_prefix="MYAPP",
138
settings_files=[
139
"config/default.toml",
140
f"config/{config_name or 'development'}.toml"
141
],
142
environments=True,
143
load_dotenv=True
144
)
145
146
# Register blueprints
147
from .views import main
148
app.register_blueprint(main)
149
150
return app
151
152
# Usage
153
app = create_app("production")
154
```
155
156
### Django Multi-Environment Setup
157
158
Configure Django for multiple environments with dynaconf.
159
160
```python
161
# settings/__init__.py
162
import os
163
import dynaconf
164
165
# Determine environment from ENV variable or default to development
166
environment = os.environ.get("DJANGO_ENV", "development")
167
168
# Configure dynaconf for Django
169
settings = dynaconf.DjangoDynaconf(
170
__name__,
171
envvar_prefix="DJANGO",
172
settings_files=[
173
"config/base.toml",
174
f"config/{environment}.toml",
175
".secrets.toml"
176
],
177
environments=True,
178
env_switcher="DJANGO_ENV",
179
load_dotenv=True
180
)
181
182
# Base Django settings
183
BASE_DIR = settings.BASE_DIR
184
SECRET_KEY = settings.SECRET_KEY
185
DEBUG = settings.DEBUG
186
187
# Database configuration from dynaconf
188
DATABASES = {
189
"default": {
190
"ENGINE": settings.DB_ENGINE,
191
"NAME": settings.DB_NAME,
192
"USER": settings.DB_USER,
193
"PASSWORD": settings.DB_PASSWORD,
194
"HOST": settings.DB_HOST,
195
"PORT": settings.DB_PORT,
196
}
197
}
198
199
# Framework-specific settings
200
INSTALLED_APPS = settings.INSTALLED_APPS
201
MIDDLEWARE = settings.MIDDLEWARE
202
ROOT_URLCONF = settings.ROOT_URLCONF
203
```
204
205
### Flask Configuration Classes
206
207
Use dynaconf with Flask configuration classes.
208
209
```python
210
from dynaconf import Dynaconf
211
212
class Config:
213
"""Base configuration using dynaconf."""
214
215
def __init__(self):
216
self.settings = Dynaconf(
217
envvar_prefix="FLASK",
218
settings_files=["config.toml"],
219
environments=True,
220
load_dotenv=True
221
)
222
223
# Map dynaconf settings to Flask config attributes
224
@property
225
def SECRET_KEY(self):
226
return self.settings.SECRET_KEY
227
228
@property
229
def SQLALCHEMY_DATABASE_URI(self):
230
return self.settings.DATABASE_URL
231
232
@property
233
def SQLALCHEMY_TRACK_MODIFICATIONS(self):
234
return self.settings.get("SQLALCHEMY_TRACK_MODIFICATIONS", False)
235
236
class DevelopmentConfig(Config):
237
"""Development configuration."""
238
239
def __init__(self):
240
super().__init__()
241
self.settings.setenv("development")
242
243
class ProductionConfig(Config):
244
"""Production configuration."""
245
246
def __init__(self):
247
super().__init__()
248
self.settings.setenv("production")
249
250
# Application factory using config classes
251
def create_app(config_name):
252
app = Flask(__name__)
253
254
config_classes = {
255
"development": DevelopmentConfig,
256
"production": ProductionConfig
257
}
258
259
config = config_classes[config_name]()
260
app.config.from_object(config)
261
262
return app
263
```
264
265
### Django Custom Settings Management
266
267
Advanced Django integration with custom settings management.
268
269
```python
270
# settings/dynaconf_settings.py
271
import dynaconf
272
from dynaconf import Validator
273
274
# Custom validators for Django settings
275
django_validators = [
276
Validator("SECRET_KEY", must_exist=True, len_min=50),
277
Validator("DEBUG", cast=bool, default=False),
278
Validator("ALLOWED_HOSTS", cast=list, default=[]),
279
Validator("DATABASE_URL", must_exist=True),
280
281
# Environment-specific validators
282
Validator("DEBUG", eq=False, env="production"),
283
Validator("ALLOWED_HOSTS", len_min=1, env="production"),
284
]
285
286
# Configure dynaconf with validation
287
settings = dynaconf.DjangoDynaconf(
288
__name__,
289
envvar_prefix="DJANGO",
290
settings_files=[
291
"config/django.toml",
292
"config/local.toml"
293
],
294
environments=True,
295
validators=django_validators,
296
load_dotenv=True
297
)
298
299
# Validate settings on load
300
try:
301
settings.validators.validate()
302
except dynaconf.ValidationError as e:
303
print(f"Django settings validation failed: {e}")
304
raise
305
306
# Django-specific settings mapping
307
DEBUG = settings.DEBUG
308
SECRET_KEY = settings.SECRET_KEY
309
ALLOWED_HOSTS = settings.ALLOWED_HOSTS
310
311
# Database configuration
312
DATABASES = {
313
"default": {
314
"ENGINE": "django.db.backends.postgresql",
315
"NAME": settings.get("DB_NAME", "myapp"),
316
"USER": settings.get("DB_USER", "postgres"),
317
"PASSWORD": settings.DB_PASSWORD,
318
"HOST": settings.get("DB_HOST", "localhost"),
319
"PORT": settings.get("DB_PORT", 5432),
320
}
321
}
322
323
# Application definition
324
INSTALLED_APPS = settings.get("INSTALLED_APPS", [
325
"django.contrib.admin",
326
"django.contrib.auth",
327
"django.contrib.contenttypes",
328
"django.contrib.sessions",
329
"django.contrib.messages",
330
"django.contrib.staticfiles",
331
])
332
```
333
334
## Best Practices
335
336
### Flask Best Practices
337
338
```python
339
# Use environment-specific configuration files
340
FlaskDynaconf(
341
app,
342
settings_files=[
343
"config/base.toml", # Base configuration
344
"config/{env}.toml", # Environment-specific
345
".secrets.toml" # Sensitive data
346
],
347
environments=True,
348
load_dotenv=True
349
)
350
351
# Access configuration through Flask's app.config
352
def get_database_config():
353
return {
354
"host": app.config.DB_HOST,
355
"port": app.config.DB_PORT,
356
"database": app.config.DB_NAME
357
}
358
```
359
360
### Django Best Practices
361
362
```python
363
# Separate settings by environment
364
# settings/base.py - Common settings
365
# settings/development.py - Development overrides
366
# settings/production.py - Production overrides
367
368
# Use validation for critical settings
369
validators = [
370
Validator("SECRET_KEY", must_exist=True),
371
Validator("DATABASES", must_exist=True),
372
Validator("ALLOWED_HOSTS", must_exist=True, env="production")
373
]
374
375
settings = dynaconf.DjangoDynaconf(
376
__name__,
377
validators=validators
378
)
379
```
380
381
### Testing Integration
382
383
```python
384
# Flask testing with dynaconf
385
def test_app_with_test_config():
386
app = create_app()
387
388
# Override configuration for testing
389
app.config.update({
390
"TESTING": True,
391
"DATABASE_URL": "sqlite:///:memory:"
392
})
393
394
with app.test_client() as client:
395
response = client.get("/")
396
assert response.status_code == 200
397
398
# Django testing with dynaconf
399
# In Django test settings
400
import dynaconf
401
402
settings = dynaconf.DjangoDynaconf(
403
__name__,
404
envvar_prefix="DJANGO_TEST",
405
settings_files=["config/test.toml"],
406
force_env="testing"
407
)
408
409
DATABASES = {
410
"default": {
411
"ENGINE": "django.db.backends.sqlite3",
412
"NAME": ":memory:"
413
}
414
}
415
```