This document includes information specific to Python in Centroid. Refer to the Centroid document for general information, including information the JSON configuration file.
The Centroid Python package is hosted at PyPi.
Install Centroid using pip with pip install centroid
or by downloading Centroid, unpacking it, and using python setup.py install
.
In Python, the centroid.Config
class exposes the following:
- Static
from_file
method - Constructor
for_environment
instance method__contains__
instance method
Note: The examples given in the following sections are based on the JSON configuration file examples in the Centroid doucment.
Using the static Config.from_file(filename)
method, you can create an instance of Config
from a JSON file, as in the example below.
# from_file.py
config = Config.from_file("config.json")
server = config.database.server_address # => "my-server.local"
To load a string instead of a file, create an instance of Config
by passing a JSON string to the Config
constructor, as in the following example.
# from_string.py
json = '{ "database": { "serverAddress": "my-server.local" } }'
config = Config(json)
server = config.database.server_address # => "my-server.local"
In the Config
instance, you can use the for_environment
instance method to retrieve the configuration values for an environment.
If you specify an environment in for_environment
, Centroid will merge the requested environment's configuration values with the values in all. Refer to Examples in the Centroid document for information on creating an environment-based JSON configuration file.
To maintain environment awareness, this call adds an environment
configuration value, unless your JSON contains an environment
(case-insensitive) property already.
With the following example, Centroid will merge the configuration for prod with the configuration for all; the result is then available from a new instance of Config
.
# for_enviroment.py
config = Config.from_file("config.json").for_environment("prod")
environment = config.environment # => "prod"
server = config.some_resource.server # => "resource-prod.local"
solution_path = config.keys.ssh # => "path/to/id_rsa.pub"
In a Config
instance, the __contains__
method allows for determining if a key exists, by using the in
and not in
operators. This method uses the same case and underscore rules as is used for value lookups.
json = '{ "database": { "serverAddress": "my-server.local" } }'
config = Config(json)
"Database" in config # => True
"does_not_exist" in config # => False