dynaconf: Configuration Management for Python.
配置文件的用途:
配置和代码分离,不同环境只修改配置即可
自己写获取配置文件方法: 有点小麻烦
toml|yaml|json|ini|py
配置文件 settings.toml
[default]
DB_NAME = "mydb.db"
a_dict = { hello = "world" }
[development]
DB_PATH = "@format {env[HOME]}/{this.DB_NAME}"
name = "developer"
[test]
DB_PATH = "@format {env[HOME]}/{this.DB_NAME}"
name = "test"
[production]
name = "admin"
初始化:自动读取 settings.toml 配置信息
qSettings = Dynaconf(
settings_files=["settings.toml", ".secrets.toml"],
environments=True,
load_dotenv=True,
)
qSettings.validators.validate()
print("settings is loaded")
如何从上面的 settings 文件中获取值:
# 直接读取
def test_config_default_value():
assert qSettings.DB_NAME == "mydb.db"
settings.a_dict.hello
从上面的 settings 文件中获取嵌套值: settings.a_dict.hello
def test_config_default_nested_value():
print(qSettings.a_dict)
assert qSettings.a_dict.hello == "world"
不同环境的值:name, 通过.env 文件配置
def test_config_environment_setting():
assert qSettings.name == "developer"
dict[key]
这种方式取值,用 dict.key
也可以取值