【发布时间】:2017-01-20 16:41:21
【问题描述】:
我正在使用 YAML 配置文件。所以这是在 Python 中加载我的配置的代码:
import os
import yaml
with open('./config.yml') as file:
config = yaml.safe_load(file)
这段代码实际上创建了一个字典。现在的问题是,为了访问我需要使用大量括号的值。
YAML:
mysql:
user:
pass: secret
Python:
import os
import yaml
with open('./config.yml') as file:
config = yaml.safe_load(file)
print(config['mysql']['user']['pass']) # <--
我更喜欢这样的东西(点符号):
config('mysql.user.pass')
所以,我的想法是利用 PyStache 的 render() 接口。
import os
import yaml
with open('./config.yml') as file:
config = yaml.safe_load(file)
import pystache
def get_config_value( yml_path, config ):
return pystache.render('{{' + yml_path + '}}', config)
get_config_value('mysql.user.pass', config)
这会是一个“好”的解决方案吗?如果没有,有什么更好的选择?
其他问题 [已解决]
我决定使用 Ilja Everilä 的解决方案。但现在我还有一个问题:如何围绕 DotConf 创建一个包装 Config 类?
以下代码不起作用,但我希望你明白我想要做什么:
class Config( DotDict ):
def __init__( self ):
with open('./config.yml') as file:
DotDict.__init__(yaml.safe_load(file))
config = Config()
print(config.django.admin.user)
错误:
AttributeError: 'super' object has no attribute '__getattr__'
解决方案
您只需要将self 传递给超类的构造函数即可。
DotDict.__init__(self, yaml.safe_load(file))
更好的解决方案 (Ilja Everilä)
super().__init__(yaml.safe_load(file))
【问题讨论】:
-
为此使用模板引擎实在是太糟糕了。请不要在任何实际应用中这样做!
-
stackoverflow.com/questions/11049117/… 似乎相关,甚至重复
标签: python python-3.x yaml