Quick Start
Installation
You can install the library from PyPI using typical methods, such as pip:
python3 -m pip install appsettings2
Usage
Using appsettings2 is straightforward:
Construct a
ConfigurationBuilderobject.Add one or more
ConfigurationProviderobjects to it.Call
build()to get aConfigurationobject populated with configuration data.
config = ConfigurationBuilder()\
.add_json('appsettings.json')\
.add_json('appsettings.Development.json', required=False)\
.add_environment()\
.build()
Provider Order
The order that providers are added to the ConfigurationBuilder is important. The configuration data populated by multiple providers is merged together, and providers appearing first will have their configuration values overwritten by providers appearing last.
With the above code snippet, consider the following configuration files:
appsettings.json:
This file comes from source-control to implement application defaults.
{
"Secret": "not-set",
"Logging": {
"Level": "WARN"
},
"AppSettings": {
"EnableSwagger": false,
"MaxBatchSize": 100
}
}
appsettings.Development.json:
This file only exists on the developer workstation to implement local settings useful for development and testing.
{
"Logging": {
"Level": "DEBUG"
},
"ConnectionStrings": {
"SampleDb": "Server=localhost;"
},
"AppSettings": {
"EnableSwagger": true
}
}
On the developer workstation, the resulting Configuration object contains the following:
print(config.get('LOGGING__LEVEL', 'WARN')) # outputs: "DEBUG"
print(config['ConnectionStrings']['SampleDb']) # outputs: "Server=localhost"
print(config.AppSettings.EnableSwagger) # outputs: True
print(config.AppSettings.MaxBatchSize) # outputs: 100
Additionally, because EnvironmentConfigurationProvider is added to the builder last (via add_environment()) it is possible to use Environment variables to overwrite any configuration values which were populated by either of the JSON providers. Consider the following bash export and associated python code, assume these are set on the developer workstation in addition to the above two configuration files:
# in `bash`, set env vars
export CONNECTIONSTRINGS__SAMPLEDB="Server=prod"
export APPSETTINGS__ENABLESWAGGER=0
# in python, check the config
print(config.ConnectionStrings.SampleDb) # outputs: "Server=prod"
print(config.AppSettings.EnableSwagger) # outputs: False
This makes it easy for developers to implement a default configuration that devops can then override as part of the Environment config of a deployment. This is a popular approach for configuring containers without leaking details into source control, particularly useful for keeping secrets like API keys and database details out of source control.