⚙️ Configuring your Dynaconf environment ------------------------------------------ 🐍 The file `config.py` was generated. on your code now use `from config import settings`. (you must have `config` importable in your PYTHONPATH).
🎛️ settings.toml created to hold your settings.
🔑 .secrets.toml created to hold your secrets.
🙈 the .secrets.toml is also included in `.gitignore` beware to not push your secrets to a public repo or use dynaconf builtin support for Vault Servers.
🎉 Dynaconf is configured! read more on https://dynaconf.com Use `dynaconf -i config.settings list` to see your settings
[development] message = 'This is in dev' foo = 1 [other] message = 'this is in other env' bar = 2
在正常使用时
1 2 3 4 5 6 7
>>> from dynaconf import settings >>> print(settings.MESSAGE) 'This is in dev' >>> print(settings.FOO) 1 >>> print(settings.BAR) AttributeError: settings object has no attribute 'BAR'
然后你可以使用from_env:
1 2 3 4 5 6
>>> print(settings.from_env('other').MESSAGE) 'This is in other env' >>> print(settings.from_env('other').BAR) 2 >>> print(settings.from_env('other').FOO) AttributeError: settings object has no attribute 'FOO'
settings.setenv('other') # 将当前的环境更改为 other 环境 assert settings.MESSAGE == 'This is in other env'
settings.setenv() # 将当前环境返回到先前的环境
3.3.3 using_env:使用上下文管理器切换环境
1 2 3 4 5 6 7 8
from dynaconf import settings
with settings.using_env('other'): # 在上下文管理器之内,切换为选择的环境 assert settings.MESSAGE == 'This is in other env'
# 在上下文管理器之外,还是默认的环境 assert settings.MESSAGE == 'This is in dev'
3.4 导出配置信息
使用命令导出 dynaconf list -o /path/to/file.yaml|toml|ini|json|py
使用代码导出
1 2 3 4 5 6 7 8 9 10
from dynaconf import loaders from dynaconf import settings from dynaconf.utils.boxing import DynaBox
# generates a dict with all the keys for `development` env data = settings.as_dict(env='development')
# writes to a file, the format is inferred by extension # can be .yaml, .toml, .ini, .json, .py loaders.write('../file.json', DynaBox(data).to_dict(), env='development')