如何在python 3中使用pyhocon动态生成Hocon conf文件? [英] How can I generate Hocon conf file dynamically using pyhocon in Python 3?

查看:825
本文介绍了如何在python 3中使用pyhocon动态生成Hocon conf文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自动化功能通过python 3脚本创建hocon配置.我读到lightbend( https://github.com/lightbend/config )建议pyhocon( https://github.com/chimpler/pyhocon ).

我在弄清楚如何创建Hocon对象并将数据作为hocon写入文件时遇到问题.对我来说,重要的是替换语法应包含在结果中.

例如,我希望文件myconfig.conf的输出看起来像这样:

{
   Environment: "dev"
   JobName: ${Environment}"-hello-bob"
}

因此,我认为有一种方法可以执行以下操作:

config2 = ConfigFactory.parse_string("{}")
config2.put("Environment", "dev")
#Some type of object for references or special syntax for ${Environment}  
config2.put("JobName", "${Environment}")

然后,在创建填充对象之后,应该有一种简单的方法可以写出一个或多个文件:

filename = "myconfig.conf"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(config2.to_hocon_str)

有没有人想办法做到这一点?该库只能用于读取数据似乎很奇怪.

解决方案

因此,我决定查看JVM(Java/Scala)库的文档( https://github. com/lightbend/config#examples-of-hocon ).在本文档中,他们对7种有效的hocon样式进行了分类.我之所以称呼这些样式,是因为如果要自动生成这些文件,我会选择一种写出并坚持使用的方式.

所有这些都是有效的HOCON.

1.以有效的JSON开头:

{
    "foo" : {
        "bar" : 10,
        "baz" : 12
    }
}

2.丢弃根括号:

"foo" : {
    "bar" : 10,
    "baz" : 12
}

3.引号:

foo : {
    bar : 10,
    baz : 12
}

4.使用=并在{:

之前将其忽略

foo {
    bar = 10,
    baz = 12
}

5.删除逗号:

foo {
    bar = 10
    baz = 12
}

6.对于未加引号的键,请使用点分符号:

foo.bar=10
foo.baz=12

7.将点符号字段放在一行上:

foo.bar=10, foo.baz=12

由于我将使用pyhocon库,因此需要在该库中寻找写入解决方案.我从chimpler的git( https://github.com/chimpler/pyhocon )中找到了一些帮助.我发现它们有两种可以简单地写出的hocon样式.一个是json,另一个是不在lightbend上面描述的列表中的东西.

样式1:纯JSON,可以通过两种方式写出巫婆:

HOCONConverter.to_json

#Using HOCONConverter.to_json
confTree = ConfigFactory.parse_string("{}")
confTree.put("Environment","Dev")
confTree.put("Test","${Environment}")

filename = "./json_coverted.conf"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(HOCONConverter.to_json(confTree))

HOCONConverter.to_json结果

{
    "Environment": "Dev",
    "Test": "${Environment}"
}

或使用json.dump

#Using json.dump
confTree = ConfigFactory.parse_string("{}")
confTree.put("Environment","Dev")
confTree.put("Test","${Environment}")
filename = "./json_dumped.conf"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(json.dumps(confTree,indent=4))

使用json.dump结果

{
  "Environment": "Dev",
  "Test": "${Environment}"
}

Pyhocon的其他样式,未按lightbend列出

# HOCONConverter.to_hocon
confTree = ConfigFactory.parse_string("{}")
confTree.put("Environment","Dev")
confTree.put("Test","${Environment}")
filename = "./hocon_coverted.txt"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(HOCONConverter.to_hocon(confTree))

Pyhocon的其他样式,未在lightbend结果中列出

Environment = "Dev"
Test = "${Environment}"

因此,要回答我自己的问题,在Python 3中使用pyhocon动态生成hocon conf文件的唯一可靠方法是使用json方法之一(转换器或转储).但这仍然是一个悬而未决的问题.问题是,将json读取到pyhocon ConfTree对象中时,它们是否可以在json中取消引用替换?

例如,如果我读取文件

{
    "Environment": "Dev",
    "Test": "${Environment}"
}

ConfTree对象是否将"Dev"作为Test的值?
不,不会.这是我的考试

filename = "json_coverted.conf"
print("Reading file{}".format(filename))
conf = ConfigFactory.parse_file(filename)
key="Test"
value=conf.get(key)
print("Key:{} Value:{}".format(key,value))

测试结果显示在屏幕上

Reading filejson_coverted.conf
Key:Test Value:${Environment}

那么,那么如何将pyhocon用于替代呢?

I would like to use automation to create the hocon configuration with python 3 scripting. I read that lightbend (https://github.com/lightbend/config) recommends pyhocon (https://github.com/chimpler/pyhocon).

I am having problems figuring out how to create an Hocon object and write the data to a file as hocon. It is important to me that the syntax for the substitution are in the result.

For example I expect the output of the file myconfig.conf to look something like this:

{
   Environment: "dev"
   JobName: ${Environment}"-hello-bob"
}

So, I assumed that there was a way to do something like this:

config2 = ConfigFactory.parse_string("{}")
config2.put("Environment", "dev")
#Some type of object for references or special syntax for ${Environment}  
config2.put("JobName", "${Environment}")

Then after creating the stuffed object there should be a simple way to write out to a file or files:

filename = "myconfig.conf"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(config2.to_hocon_str)

Has anyone figured a way to do this? It seems odd that the library can only be used for reading data only.

解决方案

So, I decided to look at documentation for JVM (Java/Scala) library (https://github.com/lightbend/config). After reading the documentation, there was a clear section on hocon examples (https://github.com/lightbend/config#examples-of-hocon). In this documentation, they categorized 7 valid hocon styles. I call these styles because if I was to automate the generation of these files, I would be picking one way to write out and sticking with it.

All of these are valid HOCON.

1.Start with valid JSON:

{
    "foo" : {
        "bar" : 10,
        "baz" : 12
    }
}

2.Drop root braces:

"foo" : {
    "bar" : 10,
    "baz" : 12
}

3.Drop quotes:

foo : {
    bar : 10,
    baz : 12
}

4.Use = and omit it before {:

foo {
    bar = 10,
    baz = 12
}

5.Remove commas:

foo {
    bar = 10
    baz = 12
}

6.Use dotted notation for unquoted keys:

foo.bar=10
foo.baz=12

7.Put the dotted-notation fields on a single line:

foo.bar=10, foo.baz=12

Because I will be using the pyhocon library, I needed to look for write solutions within the library. I found some help from chimpler's git (https://github.com/chimpler/pyhocon). What I found was that they have two hocon styles which can be simply written out. One is json and the other is something that wasn't on the list which was describe above by lightbend.

Style 1: pure JSON, witch can be written out in two ways:

HOCONConverter.to_json

#Using HOCONConverter.to_json
confTree = ConfigFactory.parse_string("{}")
confTree.put("Environment","Dev")
confTree.put("Test","${Environment}")

filename = "./json_coverted.conf"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(HOCONConverter.to_json(confTree))

HOCONConverter.to_json Result

{
    "Environment": "Dev",
    "Test": "${Environment}"
}

OR Using json.dump

#Using json.dump
confTree = ConfigFactory.parse_string("{}")
confTree.put("Environment","Dev")
confTree.put("Test","${Environment}")
filename = "./json_dumped.conf"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(json.dumps(confTree,indent=4))

Using json.dump Result

{
  "Environment": "Dev",
  "Test": "${Environment}"
}

Pyhocon's other Style, not listed by lightbend

# HOCONConverter.to_hocon
confTree = ConfigFactory.parse_string("{}")
confTree.put("Environment","Dev")
confTree.put("Test","${Environment}")
filename = "./hocon_coverted.txt"
print("Write to disk as {}".format(filename))
with open(filename, "w") as fd:
    fd.write(HOCONConverter.to_hocon(confTree))

Pyhocon's other Style, not listed by lightbend Result

Environment = "Dev"
Test = "${Environment}"

So, to answer my own question the only dependable way to generate a hocon conf file dynamically using pyhocon in Python 3 is by using one of the json methods (converter or dumps). But this still leaves an open question. The question being, will reading a json to a pyhocon ConfTree object be able dereference the substitutions when they are in the json?

For example if I read the file

{
    "Environment": "Dev",
    "Test": "${Environment}"
}

Will the ConfTree object get "Dev" as the value for Test?
No, it will not. Here is my test

filename = "json_coverted.conf"
print("Reading file{}".format(filename))
conf = ConfigFactory.parse_file(filename)
key="Test"
value=conf.get(key)
print("Key:{} Value:{}".format(key,value))

Test Result Out to screen

Reading filejson_coverted.conf
Key:Test Value:${Environment}

So, then how does one use pyhocon with substitutions?

这篇关于如何在python 3中使用pyhocon动态生成Hocon conf文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆