'Updating HOCON files using pyhocon
I've got a HOCON file template with some property-like configuration. This file is updated for different "names"(provided bu user input) and uploaded . I'm trying to build the hocon file by pulling the template, updating the necessary values and upload the updated file.
deployment {
proxy {
// Name has to be replaced with the name of the project
cluster.NAME {
property1 = [a_list]
property2.host = "hostname"
}
}
}
I'm able to update values using pyhocon:
from pyhocon import ConfigFactory
conf = ConfigFactory.parse_string(hocon_file_template)
host = "something-TEST.trial.com"
conf.put('deployment.proxy.cluster.NAME.property2.host', host)
new = HOCONConverter.convert(conf, "hocon")
However, I need to replace "NAME" in "cluster.NAME" with the user_input, say "TEST". I tried to change NAME using put , but that appends to the cluster tree as opposed to updating NAME to "TEST"
host_key = 'deployment.proxy.cluster.' ".{}.property2.host"
conf.put(host_key.format(user_input), host)
How do I update NAME to the input value(In this example, "TEST")?
Solution 1:[1]
Was able to use pop to remove remove the specified key i.e "NAME" and add the key "TEST" to the tree using put.
from pyhocon import ConfigFactory
conf = ConfigFactory.parse_string(hocon_file_template)
# Remove NAME from template
conf.pop("deployment.proxy.cluster.NAME")
host = "something-TEST.trial.com"
# Use Test to update required properties
conf.put('deployment.proxy.cluster.TEST.property2.host', host)
new = HOCONConverter.convert(conf, "hocon")
Solution 2:[2]
Separate the template from the config
deployment {
proxy {
// Name has to be replaced with the name of the project
cluster {
}
}
}
project_name {
property1 = [a_list]
property2 {
host = ${hostname}
}
}
Create the configuration in a dictionary
from pyhocon import ConfigFactory
project_name = "cool_project"
props = {'hostname': 'localhost'}
runtime_conf = ConfigFactory.from_dict(props)
conf = runtime_conf.with_fallback(
config="./app.conf",
resolve=True,
)
conf.deployment.proxy.cluster[project_name] = conf.project_name
You can also get both configurations from files and resolve with the second.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Confringo |
| Solution 2 | Rubber Duck |
