-
-
Notifications
You must be signed in to change notification settings - Fork 288
/
base.py
1512 lines (1281 loc) · 51.9 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import copy
import importlib
import inspect
import os
import re
import warnings
from collections import defaultdict
from contextlib import contextmanager
from contextlib import suppress
from pathlib import Path
from typing import Any
from typing import Callable
from dynaconf import default_settings
from dynaconf.loaders import default_loader
from dynaconf.loaders import enable_external_loaders
from dynaconf.loaders import env_loader
from dynaconf.loaders import execute_instance_hooks
from dynaconf.loaders import execute_module_hooks
from dynaconf.loaders import py_loader
from dynaconf.loaders import settings_loader
from dynaconf.loaders import yaml_loader
from dynaconf.loaders.base import SourceMetadata
from dynaconf.utils import BANNER
from dynaconf.utils import compat_kwargs
from dynaconf.utils import ensure_a_list
from dynaconf.utils import ensure_upperfied_list
from dynaconf.utils import missing
from dynaconf.utils import object_merge
from dynaconf.utils import recursively_evaluate_lazy_format
from dynaconf.utils import RENAMED_VARS
from dynaconf.utils import upperfy
from dynaconf.utils.boxing import DynaBox
from dynaconf.utils.files import find_file
from dynaconf.utils.files import glob
from dynaconf.utils.functional import empty
from dynaconf.utils.functional import LazyObject
from dynaconf.utils.parse_conf import apply_converter
from dynaconf.utils.parse_conf import boolean_fix
from dynaconf.utils.parse_conf import converters
from dynaconf.utils.parse_conf import Lazy
from dynaconf.utils.parse_conf import parse_conf_data
from dynaconf.utils.parse_conf import true_values
from dynaconf.validator import ValidationError
from dynaconf.validator import ValidatorList
from dynaconf.vendor.box.box_list import BoxList
class LazySettings(LazyObject):
"""Loads settings lazily from multiple sources:
settings = Dynaconf(
settings_files=["settings.toml"], # path/glob
environments=True, # activate layered environments
envvar_prefix="MYAPP", # `export MYAPP_FOO=bar`
env_switcher="MYAPP_MODE", # `export MYAPP_MODE=production`
load_dotenv=True, # read a .env file
)
More options available on https://www.dynaconf.com/configuration/
"""
def __init__(self, wrapped=None, **kwargs):
"""
handle initialization for the customization cases
:param wrapped: a deepcopy of this object will be wrapped (issue #596)
:param kwargs: values that overrides default_settings
"""
self._wrapper_class = kwargs.pop("_wrapper_class", Settings)
self._warn_dynaconf_global_settings = kwargs.pop(
"warn_dynaconf_global_settings", None
) # in 3.0.0 global settings is deprecated
self.__resolve_config_aliases(kwargs)
compat_kwargs(kwargs)
self._kwargs = kwargs
super().__init__()
if wrapped:
if self._django_override:
# This fixes django issue #596
self._wrapped = copy.deepcopy(wrapped)
else:
self._wrapped = wrapped
def __resolve_config_aliases(self, kwargs):
"""takes aliases for _FOR_DYNACONF configurations
e.g: ROOT_PATH='/' is transformed into `ROOT_PATH_FOR_DYNACONF`
"""
misspells = {
"settings_files": "settings_file",
"SETTINGS_FILES": "SETTINGS_FILE",
"environment": "environments",
"ENVIRONMENT": "ENVIRONMENTS",
}
for misspell, correct in misspells.items():
if misspell in kwargs:
kwargs[correct] = kwargs.pop(misspell)
for_dynaconf_keys = {
key
for key in UPPER_DEFAULT_SETTINGS
if key.endswith("_FOR_DYNACONF")
}
aliases = {
key.upper()
for key in kwargs
if f"{key.upper()}_FOR_DYNACONF" in for_dynaconf_keys
}
for alias in aliases:
value = kwargs.pop(alias, empty)
if value is empty:
value = kwargs.pop(alias.lower())
kwargs[f"{alias}_FOR_DYNACONF"] = value
def __getattr__(self, name):
"""Allow getting keys from self.store using dot notation"""
if self._wrapped is empty:
self._setup()
if name in self._wrapped._deleted: # noqa
raise AttributeError(
f"Attribute {name} was deleted, " "or belongs to different env"
)
if name not in RESERVED_ATTRS:
lowercase_mode = self._kwargs.get(
"LOWERCASE_READ_FOR_DYNACONF",
default_settings.LOWERCASE_READ_FOR_DYNACONF,
)
if lowercase_mode is True:
name = name.upper()
if (
name.isupper()
and (
self._wrapped._fresh
or name
in ensure_upperfied_list(self._wrapped.FRESH_VARS_FOR_DYNACONF)
)
and name not in UPPER_DEFAULT_SETTINGS
):
return self._wrapped.get_fresh(name)
value = getattr(self._wrapped, name)
if name not in RESERVED_ATTRS:
return recursively_evaluate_lazy_format(value, self)
return value
def __call__(self, *args, **kwargs):
"""Allow direct call of settings('val')
in place of settings.get('val')
"""
return self.get(*args, **kwargs)
@property
def _should_load_dotenv(self):
"""Chicken and egg problem, we must manually check envvar
before deciding if we are loading envvars :)"""
_environ_load_dotenv = parse_conf_data(
boolean_fix(os.environ.get("LOAD_DOTENV_FOR_DYNACONF")),
tomlfy=True,
)
return self._kwargs.get("load_dotenv", _environ_load_dotenv)
def _setup(self):
"""Initial setup, run once."""
if self._warn_dynaconf_global_settings:
warnings.warn(
"Usage of `from dynaconf import settings` is now "
"DEPRECATED in 3.0.0+. You are encouraged to change it to "
"your own instance e.g: `settings = Dynaconf(*options)`",
DeprecationWarning,
)
self._wrapper_class = Settings # Force unhooked for this
default_settings.reload(self._should_load_dotenv)
environment_variable = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = os.environ.get(environment_variable)
self._wrapped = self._wrapper_class(
settings_module=settings_module, **self._kwargs
)
def configure(self, settings_module=None, **kwargs):
"""
Allows user to reconfigure settings object passing a new settings
module or separated kwargs
:param settings_module: defines the settings file
:param kwargs: override default settings
"""
default_settings.reload(self._should_load_dotenv)
environment_var = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = settings_module or os.environ.get(environment_var)
compat_kwargs(kwargs)
kwargs.update(self._kwargs)
self._wrapped = self._wrapper_class(
settings_module=settings_module, **kwargs
)
@property
def configured(self):
"""If wrapped is configured"""
return self._wrapped is not empty
class Settings:
"""
Common logic for settings whether set by a module or by the user.
"""
dynaconf_banner = BANNER
_store = DynaBox()
def __init__(self, settings_module=None, **kwargs): # pragma: no cover
"""Execute loaders and custom initialization
:param settings_module: defines the settings file
:param kwargs: override default settings
"""
self._fresh = False
self._loaded_envs = []
self._loaded_hooks = defaultdict(dict)
self._loaded_py_modules = []
self._loaded_files = []
self._deleted = set()
self._store = DynaBox(box_settings=self)
self._env_cache = {}
self._loaded_by_loaders: dict[SourceMetadata | str, Any] = {}
self._loaders = []
self._defaults = DynaBox(box_settings=self)
self.environ = os.environ
self.SETTINGS_MODULE = None
self.filter_strategy = kwargs.get("filter_strategy", None)
self._not_installed_warnings = []
self._validate_only = kwargs.pop("validate_only", None)
self._validate_exclude = kwargs.pop("validate_exclude", None)
self._validate_only_current_env = kwargs.pop(
"validate_only_current_env", False
)
self.validators = ValidatorList(
self, validators=kwargs.pop("validators", None)
)
self._post_hooks: list[Callable] = ensure_a_list(
kwargs.get("post_hooks", [])
)
compat_kwargs(kwargs)
if settings_module:
self.set(
"SETTINGS_FILE_FOR_DYNACONF",
settings_module,
loader_identifier="init_settings_module",
)
for key, value in kwargs.items():
self.set(
key, value, loader_identifier="init_kwargs", validate=False
)
# execute loaders only after setting defaults got from kwargs
self._defaults = kwargs
# The following flags are used for when copying of settings is done
skip_loaders = kwargs.get("dynaconf_skip_loaders", False)
skip_validators = kwargs.get("dynaconf_skip_validators", False)
if not skip_loaders:
self.execute_loaders()
if not skip_validators:
self.validators.validate(
only=self._validate_only,
exclude=self._validate_exclude,
only_current_env=self._validate_only_current_env,
)
def __call__(self, *args, **kwargs):
"""Allow direct call of `settings('val')`
in place of `settings.get('val')`
"""
return self.get(*args, **kwargs)
def __setattr__(self, name, value):
"""Allow `settings.FOO = 'value'` while keeping internal attrs."""
if name in RESERVED_ATTRS:
super().__setattr__(name, value)
else:
self.set(name, value)
def __delattr__(self, name):
"""stores reference in `_deleted` for proper error management"""
self._deleted.add(name)
if hasattr(self, name):
super().__delattr__(name)
def __contains__(self, item):
"""Respond to `item in settings`"""
return item.upper() in self.store or item.lower() in self.store
def __getattribute__(self, name):
if (
name.startswith("__")
or name in RESERVED_ATTRS + UPPER_DEFAULT_SETTINGS
):
return super().__getattribute__(name)
# This is to keep the only upper case mode working
# self._store has Lazy values already evaluated
if (
name.islower()
and self._store.get("LOWERCASE_READ_FOR_DYNACONF", empty) is False
):
try:
# only matches exact casing, first levels always upper
return self._store.__getattribute__(name)
except KeyError:
return super().__getattribute__(name)
# then go to the regular .get which triggers hooks among other things
value = self.get(name, default=empty)
if value is empty:
return super().__getattribute__(name)
return value
def __getitem__(self, item):
"""Allow getting variables as dict keys `settings['KEY']`"""
value = self.get(item, default=empty)
if value is empty:
raise KeyError(f"{item} does not exist")
return value
def __setitem__(self, key, value):
"""Allow `settings['KEY'] = 'value'`"""
self.set(key, value)
@property
def store(self):
"""Gets internal storage"""
return self._store
def __dir__(self):
"""Enable auto-complete for code editors"""
return (
RESERVED_ATTRS
+ [k.lower() for k in self.keys()]
+ list(self.keys())
)
def __iter__(self):
"""Redirects to store object"""
yield from self._store
def items(self):
"""Redirects to store object"""
return self._store.items()
def keys(self):
"""Redirects to store object"""
return self.store.keys()
def values(self):
"""Redirects to store object"""
return self.store.values()
def setdefault(
self, item, default, apply_default_on_none=False, env: str = "unknown"
):
"""Returns value if exists or set it as the given default
apply_default_on_none: if True, default is set when value is None
env: used to create the source identifier
"""
value = self.get(item, empty)
# Yaml loader reads empty values as None, would we apply defaults?
global_apply_default = (
self.get("APPLY_DEFAULT_ON_NONE_FOR_DYNACONF") is not None
)
apply_default = default is not empty and (
value is empty
or (
value is None
and (
apply_default_on_none is True
or global_apply_default is True
)
)
)
loader_identifier = SourceMetadata("setdefault", "unique", env.lower())
if apply_default:
self.set(
item,
default,
loader_identifier=loader_identifier,
tomlfy=True,
)
return default
return value
def as_dict(self, env=None, internal=False):
"""Returns a dictionary with set key and values.
:param env: Str env name, default self.current_env `DEVELOPMENT`
:param internal: bool - should include dynaconf internal vars?
"""
ctx_mgr = suppress() if env is None else self.using_env(env)
with ctx_mgr:
data = self.store.to_dict().copy()
# if not internal remove internal settings
if not internal:
for name in UPPER_DEFAULT_SETTINGS:
data.pop(name, None)
return data
to_dict = as_dict # backwards compatibility
def _dotted_get(
self, dotted_key, default=None, parent=None, cast=None, **kwargs
):
"""
Perform dotted key lookups and keep track of where we are.
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param parent: Is there a pre-loaded parent in a nested data?
"""
# if parent is not traverseable raise error
if parent and not hasattr(parent, "get"):
raise AttributeError(
f"cannot lookup {dotted_key!r} from {type(parent).__name__!r}"
)
split_key = dotted_key.split(".")
name, keys = split_key[0], split_key[1:]
result = self.get(name, default=default, parent=parent, **kwargs)
# If we've reached the end, or parent key not found, then return result
if not keys or result == default:
if cast and cast in converters:
return apply_converter(cast, result, box_settings=self)
elif cast is True:
return parse_conf_data(result, tomlfy=True, box_settings=self)
return result
# If we've still got key elements to traverse, let's do that.
return self._dotted_get(
".".join(keys), default=default, parent=result, cast=cast, **kwargs
)
def get(
self,
key,
default=None,
cast=None,
fresh=False,
dotted_lookup=empty,
parent=None,
sysenv_fallback=None,
):
"""
Get a value from settings store, this is the preferred way to access::
>>> from dynaconf import settings
>>> settings.get('KEY')
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
:param fresh: Should reload from loaders store before access?
:param dotted_lookup: Should perform dotted-path lookup?
:param parent: Is there a pre-loaded parent in a nested data?
:param sysenv_fallback: Should fallback to system environ if not found?
:return: The value if found, default or None
"""
if sysenv_fallback is None:
sysenv_fallback = self._store.get("SYSENV_FALLBACK_FOR_DYNACONF")
nested_sep = self._store.get("NESTED_SEPARATOR_FOR_DYNACONF")
if isinstance(key, str):
if nested_sep and nested_sep in key:
# turn FOO__bar__ZAZ in `FOO.bar.ZAZ`
key = key.replace(nested_sep, ".")
if dotted_lookup is empty:
dotted_lookup = self._store.get("DOTTED_LOOKUP_FOR_DYNACONF")
if "." in key and dotted_lookup:
return self._dotted_get(
dotted_key=key,
default=default,
cast=cast,
fresh=fresh,
parent=parent,
)
key = upperfy(key)
# handles system environment fallback
if default is None:
key_in_sysenv_fallback_list = isinstance(
sysenv_fallback, list
) and key in [upperfy(k) for k in sysenv_fallback]
if sysenv_fallback is True or key_in_sysenv_fallback_list:
default = self.get_environ(key, cast=True)
# default values should behave exactly Dynaconf parsed values
if default is not None:
if isinstance(default, list):
default = BoxList(default)
elif isinstance(default, dict):
default = DynaBox(default)
if key in self._deleted:
return default
if (
fresh
or self._fresh
or key
in ensure_upperfied_list(
getattr(self, "FRESH_VARS_FOR_DYNACONF", ())
)
) and key not in UPPER_DEFAULT_SETTINGS:
self.unset(key)
self.execute_loaders(key=key)
data = (parent or self.store).get(key, default)
if cast:
data = apply_converter(cast, data, box_settings=self)
return data
def exists(self, key, fresh=False):
"""Check if key exists
:param key: the name of setting variable
:param fresh: if key should be taken from source directly
:return: Boolean
"""
key = upperfy(key)
if key in self._deleted:
return False
return self.get(key, fresh=fresh, default=missing) is not missing
def get_fresh(self, key, default=None, cast=None):
"""This is a shortcut to `get(key, fresh=True)`. always reload from
loaders store before getting the var.
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
:return: The value if found, default or None
"""
return self.get(key, default=default, cast=cast, fresh=True)
def get_environ(self, key, default=None, cast=None):
"""Get value from environment variable using os.environ.get
:param key: The name of the setting value, will always be upper case
:param default: In case of not found it will be returned
:param cast: Should cast in to @int, @float, @bool or @json ?
or cast must be true to use cast inference
:return: The value if found, default or None
"""
key = upperfy(key)
data = self.environ.get(key, default)
if data:
if cast in converters:
data = apply_converter(cast, data, box_settings=self)
elif cast is True:
data = parse_conf_data(
boolean_fix(data), tomlfy=True, box_settings=self
)
return data
def exists_in_environ(self, key):
"""Return True if env variable is exported"""
return upperfy(key) in self.environ
def as_bool(self, key):
"""Partial method for get with bool cast"""
return self.get(key, cast="@bool")
def as_int(self, key):
"""Partial method for get with int cast"""
return self.get(key, cast="@int")
def as_float(self, key):
"""Partial method for get with float cast"""
return self.get(key, cast="@float")
def as_json(self, key):
"""Partial method for get with json cast"""
return self.get(key, cast="@json")
@property
def loaded_envs(self):
"""Get or create internal loaded envs list"""
if not self._loaded_envs:
self._loaded_envs = []
return self._loaded_envs
@loaded_envs.setter
def loaded_envs(self, value):
"""Setter for env list"""
self._loaded_envs = value
# compat
loaded_namespaces = loaded_envs
@property
def loaded_by_loaders(self): # pragma: no cover
"""Gets the internal mapping of LOADER -> values"""
return self._loaded_by_loaders
def from_env(self, env="", keep=False, **kwargs):
"""Return a new isolated settings object pointing to specified env.
Example of settings.toml::
[development]
message = 'This is in dev'
[other]
message = 'this is in other env'
Program::
>>> from dynaconf import settings
>>> print(settings.MESSAGE)
'This is in dev'
>>> print(settings.from_env('other').MESSAGE)
'This is in other env'
# The existing settings object remains the same.
>>> print(settings.MESSAGE)
'This is in dev'
Arguments:
env {str} -- Env to load (development, production, custom)
Keyword Arguments:
keep {bool} -- Keep pre-existing values (default: {False})
kwargs {dict} -- Passed directly to new instance.
"""
cache_key = f"{env}_{keep}_{kwargs}"
if cache_key in self._env_cache:
return self._env_cache[cache_key]
new_data = {
key: self.get(key)
for key in UPPER_DEFAULT_SETTINGS
if key not in RENAMED_VARS
}
if self.filter_strategy:
# Retain the filtering strategy when switching environments
new_data["filter_strategy"] = self.filter_strategy
# This is here for backwards compatibility
# To be removed on 4.x.x
default_settings_paths = self.get("default_settings_paths")
if default_settings_paths: # pragma: no cover
new_data["default_settings_paths"] = default_settings_paths
if keep:
# keep existing values from current env
new_data.update(
{
key: value
for key, value in self.store.to_dict().copy().items()
if key.isupper() and key not in RENAMED_VARS
}
)
new_data.update(kwargs)
new_data["FORCE_ENV_FOR_DYNACONF"] = env
new_settings = LazySettings(**new_data)
self._env_cache[cache_key] = new_settings
# update source metadata for inspecting
self._loaded_by_loaders.update(new_settings._loaded_by_loaders)
return new_settings
@contextmanager
def using_env(self, env, clean=True, silent=True, filename=None):
"""
This context manager allows the contextual use of a different env
Example of settings.toml::
[development]
message = 'This is in dev'
[other]
message = 'this is in other env'
Program::
>>> from dynaconf import settings
>>> print settings.MESSAGE
'This is in dev'
>>> with settings.using_env('OTHER'):
... print settings.MESSAGE
'this is in other env'
:param env: Upper case name of env without any _
:param clean: If preloaded vars should be cleaned
:param silent: Silence errors
:param filename: Custom filename to load (optional)
:return: context
"""
try:
self.setenv(env, clean=clean, silent=silent, filename=filename)
yield
finally:
if env.lower() != self.ENV_FOR_DYNACONF.lower():
del self.loaded_envs[-1]
self.setenv(self.current_env, clean=clean, filename=filename)
# compat
using_namespace = using_env
@contextmanager
def fresh(self):
"""
this context manager force the load of a key direct from the store::
$ export DYNACONF_VALUE='Original'
>>> from dynaconf import settings
>>> print settings.VALUE
'Original'
$ export DYNACONF_VALUE='Changed Value'
>>> print settings.VALUE # will not be reloaded from env vars
'Original
>>> with settings.fresh(): # inside this context all is reloaded
... print settings.VALUE
'Changed Value'
an alternative is using `settings.get_fresh(key)`
:return: context
"""
self._fresh = True
yield
self._fresh = False
@property
def current_env(self):
"""Return the current active env"""
if self.ENVIRONMENTS_FOR_DYNACONF is False:
return self.MAIN_ENV_FOR_DYNACONF.lower()
if self.FORCE_ENV_FOR_DYNACONF is not None:
self.ENV_FOR_DYNACONF = self.FORCE_ENV_FOR_DYNACONF
return self.FORCE_ENV_FOR_DYNACONF
try:
return self.loaded_envs[-1]
except IndexError:
return self.ENV_FOR_DYNACONF
# compat
current_namespace = current_env
@property
def settings_module(self):
"""Gets SETTINGS_MODULE variable"""
settings_module = parse_conf_data(
os.environ.get(
self.ENVVAR_FOR_DYNACONF, self.SETTINGS_FILE_FOR_DYNACONF
),
tomlfy=True,
box_settings=self,
)
if settings_module != getattr(self, "SETTINGS_MODULE", None):
self.set(
"SETTINGS_MODULE",
settings_module,
loader_identifier="settings_module_method",
)
# This is for backewards compatibility, to be removed on 4.x.x
if not self.SETTINGS_MODULE and self.get("default_settings_paths"):
self.SETTINGS_MODULE = self.get("default_settings_paths")
return self.SETTINGS_MODULE
# Backwards compatibility see #169
settings_file = settings_module
def setenv(self, env=None, clean=True, silent=True, filename=None):
"""Used to interactively change the env
Example of settings.toml::
[development]
message = 'This is in dev'
[other]
message = 'this is in other env'
Program::
>>> from dynaconf import settings
>>> print settings.MESSAGE
'This is in dev'
>>> with settings.using_env('OTHER'):
... print settings.MESSAGE
'this is in other env'
:param env: Upper case name of env without any _
:param clean: If preloaded vars should be cleaned
:param silent: Silence errors
:param filename: Custom filename to load (optional)
:return: context
"""
env = env or self.ENV_FOR_DYNACONF
if not isinstance(env, str) or " " in env:
raise ValueError("env should be a string without spaces")
env = env.upper()
if env != self.ENV_FOR_DYNACONF:
self.loaded_envs.append(env)
else:
self.loaded_envs = []
if clean:
self.clean(env=env)
self.execute_loaders(env=env, silent=silent, filename=filename)
# compat
namespace = setenv
def clean(self, *args, **kwargs):
"""Clean all loaded values to reload when switching envs"""
for key in list(self.store.keys()):
self.unset(key)
def unset(self, key, force=False):
"""Unset on all references
:param key: The key to be unset
:param force: Bypass default checks and force unset
"""
key = upperfy(key.strip())
if (
key not in UPPER_DEFAULT_SETTINGS
and key not in self._defaults
or force
):
with suppress(KeyError, AttributeError):
# AttributeError can happen when a LazyValue consumes
# a previously deleted key
delattr(self, key)
del self.store[key]
def unset_all(self, keys, force=False): # pragma: no cover
"""Unset based on a list of keys
:param keys: a list of keys
:param force: Bypass default checks and force unset
"""
for key in keys:
self.unset(key, force=force)
def _dotted_set(
self, dotted_key, value, tomlfy=False, validate=empty, **kwargs
):
"""Sets dotted keys as nested dictionaries.
Dotted set will always reassign the value, to merge use `@merge` token
Arguments:
dotted_key {str} -- A traversal name e.g: foo.bar.zaz
value {Any} -- The value to set to the nested value.
Keyword Arguments:
tomlfy {bool} -- Perform toml parsing (default: {False})
validate {bool} --
"""
if validate is empty:
validate = self.get(
"VALIDATE_ON_UPDATE_FOR_DYNACONF"
) # pragma: nocover
# Add a "." before "[" to help splitting
split_keys = dotted_key.replace("[", ".[").split(".")
existing_data = self.get(split_keys[0], {})
new_data = tree = DynaBox(box_settings=self)
value = parse_conf_data(value, tomlfy=tomlfy, box_settings=self)
for n, k in enumerate(split_keys):
is_not_end = n < (len(split_keys) - 1)
if is_not_end:
next_default = [] if "[" in split_keys[n + 1] else {}
if "[" not in k: # accessing field of a dict
if is_not_end:
tree = tree.setdefault(k, next_default) # get next
else:
tree[k] = value # assign value
elif k.startswith("[") and k.endswith(
"]"
): # accessing index of a list
index = int(k.replace("[", "").replace("]", ""))
# This makes sure we can assign any arbitrary index
tree.extend([next_default] * (index + 1))
if is_not_end:
tree = tree[index] # get at index
else:
tree[index] = value # assign value
else: # odd cases like [2]0
raise (ValueError("Invalid field:", k))
if existing_data:
old_data = DynaBox(
{split_keys[0]: existing_data}, box_settings=self
)
new_data = object_merge(
old=old_data,
new=new_data,
full_path=split_keys,
list_merge="deep", # when to use deep / shallow replace?
)
self.update(data=new_data, tomlfy=tomlfy, validate=validate, **kwargs)
def set(
self,
key,
value,
loader_identifier: SourceMetadata | str | None = None,
tomlfy=False,
dotted_lookup=empty,
is_secret="DeprecatedArgument", # noqa
validate=empty,
merge=empty,
):
"""Set a value storing references for the loader
:param key: The key to store. Can be of any type.
:param value: The raw value to parse and store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
Or instance of SourceMetadata
:param tomlfy: Bool define if value is parsed by toml (defaults False)
:param merge: Bool define if existing nested data will be merged.
:param validate: Bool define if validation will be triggered
"""
# Ensure source_metadata always is set even if set is called
# without a loader_identifier
if isinstance(loader_identifier, str) or loader_identifier is None:
source_metadata = SourceMetadata(
loader="set_method",
identifier=loader_identifier or "undefined",
merged=merge is True,
)
else: # loader identifier must be a SourceMetadata instance
source_metadata = loader_identifier
if validate is empty:
validate = self.get("VALIDATE_ON_UPDATE_FOR_DYNACONF")
if dotted_lookup is empty:
dotted_lookup = self.get("DOTTED_LOOKUP_FOR_DYNACONF")
# Do index replacement first
nested_ind = self.get("INDEX_SEPARATOR_FOR_DYNACONF")
# DYNACONF_DATA__a___0__key___2__subkey ->
# DYNACONF_DATA__a[0]__key[2]__subkey
if nested_ind and isinstance(key, str):
nested_ind = rf"{nested_ind}(\d+)"
key = re.sub(nested_ind, r"[\1]", key)
nested_sep = self.get("NESTED_SEPARATOR_FOR_DYNACONF")
if isinstance(key, str):
if nested_sep and nested_sep in key:
key = key.replace(nested_sep, ".") # FOO__bar -> FOO.bar
if ("." in key or "[" in key) and dotted_lookup is True:
return self._dotted_set(
key,
value,
loader_identifier=source_metadata,
tomlfy=tomlfy,
validate=validate,
)
key = upperfy(key.strip())
parsed = parse_conf_data(value, tomlfy=tomlfy, box_settings=self)