dynaconf package¶
Subpackages¶
- dynaconf.contrib package
- dynaconf.loaders package
- Submodules
- dynaconf.loaders.env_loader module
- dynaconf.loaders.redis_loader module
- dynaconf.loaders.vault_loader module
- dynaconf.loaders.yaml_loader module
- dynaconf.loaders.toml_loader module
- dynaconf.loaders.py_loader module
- dynaconf.loaders.json_loader module
- dynaconf.loaders.ini_loader module
- dynaconf.loaders.base
- Module contents
- dynaconf.utils package
Submodules¶
dynaconf.base module¶
-
class
dynaconf.base.
LazySettings
(**kwargs)[source]¶ Bases:
dynaconf.utils.functional.LazyObject
When you do:
>>> from dynaconf import settings
a LazySettings is imported and is initialized with only default_settings.
Then when you first access a value, this will be set up and loaders will be executes looking for default config files or the file defined in SETTINGS_FILE_FOR_DYNACONF variable:
>>> settings.SETTINGS_FILE_FOR_DYNACONF
Or when you call:
>>> settings.configure(settings_module='/tmp/settings.py')
You can define in your settings module a list of loaders to get values from different stores. By default it will try environment variables starting with ENVVAR_PREFIX_FOR_DYNACONF (by defaulf DYNACONF_)
You can also import this directly and customize it. in a file proj/conf.py:
>>> from dynaconf import LazySettings >>> config = LazySettings(ENV_FOR_DYNACONF='PROJ', ... LOADERS_FOR_DYNACONF=[ ... 'dynaconf.loaders.env_loader', ... 'dynaconf.loaders.redis_loader' ... ])
save common values in a settings file:
$ echo "SERVER_IP = '10.10.10.10'" > proj/settings.py
or use .toml|.yaml|.ini|.json
save sensitive values in .secrets.{py|toml|yaml|ini|json} or export as DYNACONF global environment variable:
$ export DYNACONF_SERVER_PASSWD='super_secret' >>> # from proj.conf import config >>> print config.SERVER_IP >>> print config.SERVER_PASSWD
and now it reads all variables starting with DYNACONF_ from envvars and all values in a hash called DYNACONF_PROJ in redis
-
configure
(settings_module=None, **kwargs)[source]¶ Allows user to reconfigure settings object passing a new settings module or separated kwargs
Parameters: - settings_module – defines the setttings file
- kwargs – override default settings
-
configured
¶ If wrapped is configured
-
-
class
dynaconf.base.
Settings
(settings_module=None, **kwargs)[source]¶ Bases:
object
Common logic for settings whether set by a module or by the user.
-
as_dict
(env=None, internal=False)[source]¶ Returns a dictionary with set key and values.
Parameters: - env – Str env name, default self.current_env DEVELOPMENT
- internal – bool - should include dynaconf internal vars?
-
current_env
¶ Return the current active env
-
current_namespace
¶ Return the current active env
-
execute_loaders
(env=None, silent=None, key=None, filename=None)[source]¶ Execute all internal and registered loaders
Parameters: - env – The environment to load
- silent – If loading erros is silenced
- key – if provided load a single key
- filename – optional custom filename to load
-
exists
(key, fresh=False)[source]¶ Check if key exists
Parameters: - key – the name of setting variable
- fresh – if key should be taken from source direclty
Returns: Boolean
-
flag
(key, env=None)[source]¶ Feature flagging system write flags to redis $ dynaconf write redis -s DASHBOARD=1 -e premiumuser meaning: Any premium user has DASHBOARD feature enabled
In your program do:
# premium user has access to dashboard? >>> if settings.flag('dashboard', 'premiumuser'): ... activate_dashboard()
The value is ensured to be loaded fresh from redis server
It also works with file settings but the recommended is redis as the data can be loaded once it is updated.
Parameters: - key – The flag name
- env – The env to look for
-
fresh
()[source]¶ 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)
Returns: context
-
from_env
(env, keep=False, **kwargs)[source]¶ 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.
-
get
(key, default=None, cast=None, fresh=False, dotted_lookup=True, parent=None)[source]¶ Get a value from settings store, this is the prefered way to access:
>>> from dynaconf import settings >>> settings.get('KEY')
Parameters: - key – The name of the setting value, will always be upper case
- default – In case of not found it will be returned
- cast – Should cast in to @int, @float, @bool or @json ?
- fresh – Should reload from loaders store before access?
- dotted_lookup – Should perform dotted-path lookup?
- parent – Is there a pre-loaded parent in a nested data?
Returns: The value if found, default or None
-
get_environ
(key, default=None, cast=None)[source]¶ Get value from environment variable using os.environ.get
Parameters: - key – The name of the setting value, will always be upper case
- default – In case of not found it will be returned
- cast – Should cast in to @int, @float, @bool or @json ? or cast must be true to use cast inference
Returns: The value if found, default or None
-
get_fresh
(key, default=None, cast=None)[source]¶ This is a shortcut to get(key, fresh=True). always reload from loaders store before getting the var.
Parameters: - key – The name of the setting value, will always be upper case
- default – In case of not found it will be returned
- cast – Should cast in to @int, @float, @bool or @json ?
Returns: The value if found, default or None
-
load_extra_yaml
(env, silent, key)[source]¶ This is deprecated, kept for compat
Deprecated since version 1.0.0: Use multiple settings or INCLUDES_FOR_DYNACONF files instead.
-
load_file
(path=None, env=None, silent=True, key=None)[source]¶ Programmatically load files from
path
.Parameters: - path – A single filename or a file list
- env – Which env to load from file (default current_env)
- silent – Should raise errors?
- key – Load a single key?
-
loaded_by_loaders
¶ Gets the internal mapping of LOADER -> values
-
loaded_envs
¶ Get or create internal loaded envs list
-
loaded_namespaces
¶ Get or create internal loaded envs list
-
loaders
¶ Return available loaders
-
logger
¶ Get or create inner logger
-
namespace
(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'
Parameters: - env – Upper case name of env without any _
- clean – If preloaded vars should be cleaned
- silent – Silence errors
- filename – Custom filename to load (optional)
Returns: context
-
populate_obj
(obj, keys=None, ignore=None)[source]¶ Given the obj populate it using self.store items.
Parameters: - obj – An object to be populated, a class instance.
- keys – A list of keys to be included.
- ignore – A list of keys to be excluded.
-
set
(key, value, loader_identifier=None, tomlfy=False, dotted_lookup=True, is_secret=False, merge=False)[source]¶ Set a value storing references for the loader
Parameters: - key – The key to store
- value – The value to store
- loader_identifier – Optional loader name e.g: toml, yaml etc.
- tomlfy – Bool define if value is parsed by toml (defaults False)
- is_secret – Bool define if secret values is hidden on logs.
- merge – Bool define if existing nested data will be merged.
-
setenv
(env=None, clean=True, silent=True, filename=None)[source]¶ 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'
Parameters: - env – Upper case name of env without any _
- clean – If preloaded vars should be cleaned
- silent – Silence errors
- filename – Custom filename to load (optional)
Returns: context
-
settings_file
¶ Gets SETTINGS_MODULE variable
-
settings_module
¶ Gets SETTINGS_MODULE variable
-
store
¶ Gets internal storage
-
to_dict
(env=None, internal=False)¶ Returns a dictionary with set key and values.
Parameters: - env – Str env name, default self.current_env DEVELOPMENT
- internal – bool - should include dynaconf internal vars?
-
unset
(key, force=False)[source]¶ Unset on all references
Parameters: - key – The key to be unset
- force – Bypass default checks and force unset
-
unset_all
(keys, force=False)[source]¶ Unset based on a list of keys
Parameters: - keys – a list of keys
- force – Bypass default checks and force unset
-
update
(data=None, loader_identifier=None, tomlfy=False, is_secret=False, merge=False, **kwargs)[source]¶ Update values in the current settings object without saving in stores:
>>> from dynaconf import settings >>> print settings.NAME 'Bruno' >>> settings.update({'NAME': 'John'}, other_value=1) >>> print settings.NAME 'John' >>> print settings.OTHER_VALUE 1
Parameters: - data – Data to be updated
- loader_identifier – Only to be used by custom loaders
- tomlfy – Bool define if value is parsed by toml (defaults False)
- merge – Bool define if existing nested data will be merged.
- kwargs – extra values to update
Returns: None
-
using_env
(env, clean=True, silent=True, filename=None)[source]¶ 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'
Parameters: - env – Upper case name of env without any _
- clean – If preloaded vars should be cleaned
- silent – Silence errors
- filename – Custom filename to load (optional)
Returns: context
-
using_namespace
(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'
Parameters: - env – Upper case name of env without any _
- clean – If preloaded vars should be cleaned
- silent – Silence errors
- filename – Custom filename to load (optional)
Returns: context
-
validators
¶ Gets or creates validator wrapper
-
dynaconf.cli module¶
-
dynaconf.cli.
import_settings
(dotted_path)[source]¶ Import settings instance from python dotted path.
Last item in dotted path must be settings instace.
Example: import_settings(‘path.to.settings’)
-
dynaconf.cli.
set_settings
(instance=None)[source]¶ Pick correct settings instance and set it to a global variable.
Shows dynaconf awesome banner
dynaconf.default_settings module¶
dynaconf.constants module¶
dynaconf.test_settings module¶
dynaconf.validator module¶
-
class
dynaconf.validator.
Validator
(*names, must_exist=None, condition=None, when=None, env=None, messages=None, **operations)[source]¶ Bases:
object
Validators are conditions attached to settings variables names or patterns:
Validator('MESSAGE', must_exist=True, eq='Hello World')
The above ensure MESSAGE is available in default env and is equal to ‘Hello World’
names are a one (or more) names or patterns:
Validator('NAME') Validator('NAME', 'OTHER_NAME', 'EVEN_OTHER') Validator(r'^NAME', r'OTHER./*')
The operations are:
eq: value == other ne: value != other gt: value > other lt: value < other gte: value >= other lte: value <= other is_type_of: isinstance(value, type) is_in: value in sequence is_not_in: value not in sequence identity: value is other
env is which env to be checked, can be a list or default is used.
when holds a validator and its return decides if validator runs or not:
Validator('NAME', must_exist=True, when=Validator('OTHER', eq=2)) # NAME is required only if OTHER eq to 2 # When the very first thing to be performed when passed. # if no env is passed to `when` it is inherited
must_exist is exists requirement. (executed after when):
settings.exists(value)
condition is a callable to be executed and return boolean:
Validator('NAME', condition=lambda x: x == 1) # it is executed before operations.
-
default_messages
= mappingproxy({'must_exist_true': '{name} is required in env {env}', 'must_exist_false': '{name} cannot exists in env {env}', 'condition': '{name} invalid for {function}({value}) in env {env}', 'operations': '{name} must {operation} {op_value} but it is {value} in env {env}'})¶
-
dynaconf.validator_conditions module¶
Implement basic assertions to be used in assertion action
Module contents¶
-
class
dynaconf.
LazySettings
(**kwargs)[source]¶ Bases:
dynaconf.utils.functional.LazyObject
When you do:
>>> from dynaconf import settings
a LazySettings is imported and is initialized with only default_settings.
Then when you first access a value, this will be set up and loaders will be executes looking for default config files or the file defined in SETTINGS_FILE_FOR_DYNACONF variable:
>>> settings.SETTINGS_FILE_FOR_DYNACONF
Or when you call:
>>> settings.configure(settings_module='/tmp/settings.py')
You can define in your settings module a list of loaders to get values from different stores. By default it will try environment variables starting with ENVVAR_PREFIX_FOR_DYNACONF (by defaulf DYNACONF_)
You can also import this directly and customize it. in a file proj/conf.py:
>>> from dynaconf import LazySettings >>> config = LazySettings(ENV_FOR_DYNACONF='PROJ', ... LOADERS_FOR_DYNACONF=[ ... 'dynaconf.loaders.env_loader', ... 'dynaconf.loaders.redis_loader' ... ])
save common values in a settings file:
$ echo "SERVER_IP = '10.10.10.10'" > proj/settings.py
or use .toml|.yaml|.ini|.json
save sensitive values in .secrets.{py|toml|yaml|ini|json} or export as DYNACONF global environment variable:
$ export DYNACONF_SERVER_PASSWD='super_secret' >>> # from proj.conf import config >>> print config.SERVER_IP >>> print config.SERVER_PASSWD
and now it reads all variables starting with DYNACONF_ from envvars and all values in a hash called DYNACONF_PROJ in redis
-
configure
(settings_module=None, **kwargs)[source]¶ Allows user to reconfigure settings object passing a new settings module or separated kwargs
Parameters: - settings_module – defines the setttings file
- kwargs – override default settings
-
configured
¶ If wrapped is configured
-
-
class
dynaconf.
Validator
(*names, must_exist=None, condition=None, when=None, env=None, messages=None, **operations)[source]¶ Bases:
object
Validators are conditions attached to settings variables names or patterns:
Validator('MESSAGE', must_exist=True, eq='Hello World')
The above ensure MESSAGE is available in default env and is equal to ‘Hello World’
names are a one (or more) names or patterns:
Validator('NAME') Validator('NAME', 'OTHER_NAME', 'EVEN_OTHER') Validator(r'^NAME', r'OTHER./*')
The operations are:
eq: value == other ne: value != other gt: value > other lt: value < other gte: value >= other lte: value <= other is_type_of: isinstance(value, type) is_in: value in sequence is_not_in: value not in sequence identity: value is other
env is which env to be checked, can be a list or default is used.
when holds a validator and its return decides if validator runs or not:
Validator('NAME', must_exist=True, when=Validator('OTHER', eq=2)) # NAME is required only if OTHER eq to 2 # When the very first thing to be performed when passed. # if no env is passed to `when` it is inherited
must_exist is exists requirement. (executed after when):
settings.exists(value)
condition is a callable to be executed and return boolean:
Validator('NAME', condition=lambda x: x == 1) # it is executed before operations.
-
default_messages
= mappingproxy({'must_exist_true': '{name} is required in env {env}', 'must_exist_false': '{name} cannot exists in env {env}', 'condition': '{name} invalid for {function}({value}) in env {env}', 'operations': '{name} must {operation} {op_value} but it is {value} in env {env}'})¶
-
-
class
dynaconf.
FlaskDynaconf
(app=None, instance_relative_config=False, dynaconf_instance=None, **kwargs)[source]¶ Bases:
object
The arguments are. app = The created app dynaconf_args = Extra args to be passed to Dynaconf (validator for example)
All other values are stored as config vars specially:
ENVVAR_PREFIX_FOR_DYNACONF = env prefix for your envvars to be loaded example: if you set to `MYSITE` then export MYSITE_SQL_PORT='@int 5445' with that exported to env you access using: app.config.SQL_PORT app.config.get('SQL_PORT') app.config.get('sql_port') # get is case insensitive app.config['SQL_PORT'] Dynaconf uses `@int, @bool, @float, @json` to cast env vars SETTINGS_FILE_FOR_DYNACONF = The name of the module or file to use as default to load settings. If nothing is passed it will be `settings.*` or value found in `ENVVAR_FOR_DYNACONF` Dynaconf supports .py, .yml, .toml, ini, json
- ATTENTION: Take a look at settings.yml and .secrets.yml to know the
- required settings format.
Settings load order in Dynaconf:
- Load all defaults and Flask defaults
- Load all passed variables when applying FlaskDynaconf
- Update with data in settings files
- Update with data in environment vars ENVVAR_FOR_DYNACONF_
TOML files are very useful to have envd settings, lets say, production and development.
You can also achieve the same using multiple .py files naming as settings.py, production_settings.py and development_settings.py (see examples/validator)
Example:
app = Flask(__name__) FlaskDynaconf( app, ENV_FOR_DYNACONF='MYSITE', SETTINGS_FILE_FOR_DYNACONF='settings.yml', EXTRA_VALUE='You can add aditional config vars here' )
Take a look at examples/flask in Dynaconf repository
-
dynaconf.
DjangoDynaconf
(django_settings_module_name=None, **kwargs)¶