【问题标题】:How to load JSON config file in cement python app?如何在水泥 python 应用程序中加载 JSON 配置文件?
【发布时间】:2017-11-02 08:05:48
【问题描述】:

我刚刚开始使用水泥作为 python 框架。应用程序的默认配置似乎不是 JSON。

似乎 Cement 有 JsonConfigHandler() 类可以将 JSON 配置加载到应用程序中。我在我的应用程序中使用了以下代码:

ins = JsonConfigHandler()
ins.parse_file('/etc/luna/luna.conf')

但它给出了以下错误:

    return self._parse_file(file_path)
  File "/Library/Python/2.7/site-packages/cement/ext/ext_json.py", line 243, in _parse_file
    self.merge(self._json.load(open(file_path)))
AttributeError: 'NoneType' object has no attribute 'load'

我应该如何在水泥应用中加载 JSON 配置文件?

默认情况下,我使用app.config.parse_file('/etc/my_app/app.conf') 加载配置没有问题,配置文件包含:

[connection]
host=172.16.131.12

【问题讨论】:

    标签: python json configuration cement


    【解决方案1】:

    JSON 文件/etc/luna/luna.conf:

    {
        "connection": {
            "host": "172.16.131.12"
        }
    }
    

    Python:

    from cement.core.foundation import CementApp
    from cement.ext.ext_json import JsonConfigHandler
    
    app = CementApp('test', config_handler=JsonConfigHandler,
                    config_files=['/etc/luna/luna.conf'])
    app.setup()
    
    print(app.config.get('connection', 'host'))
    

    输出172.16.131.12


    旧答案,请忽略

    不知道库,但是看代码好像要先调用_setup()方法:

    ins = JsonConfigHandler()
    ins._setup(app)
    ins.parse_file('/etc/luna/luna.conf')
    

    【讨论】:

    • 在 Cement 框架内部调用受保护的方法似乎根本不是好的做法。我确信有更好的方法可以将 JSON 配置输入水泥配置处理程序。
    • 你是绝对正确的@ALH,你能检查我添加的编辑是否有效吗?
    • @ALH 进行了另一次编辑,它现在对我来说可以正常工作了。让我知道这是否适合您,我会编辑答案以清楚地反映正确的解决方案。
    • 感谢您的回复,如果在 JSON 中我有一个像 "modern": "yes" 这样的密钥,我应该如何检索它?似乎配置应该有一个部分!我无法通过 get() 方法获取modern
    • 我认为不可能,如果您查看代码,cement.ext.ext_json.JsonConfigHandler#_parse_file 方法会加载 JSON 配置文件 (self._json.load(open(file_path))) 并将 JSON 对象(字典)传递给 @ 987654331@,此方法迭代 JSON dict 的键值对并跳过值不是 dict 的键值对。我想您必须将"modern": "yes" 放在一个部分中。我没有找到这方面的文档,这都是我通过阅读代码所理解的,因此我可能是错的。
    【解决方案2】:

    很抱歉没有在此之上,但这是官方回复(主要开发人员):

    您只需包含json 扩展名,然后将CementApp.Meta.config_handler 设置为json

    from cement.core.foundation import CementApp
    
    class MyApp(CementApp):
        class Meta:
            label = 'myapp'
            extensions = ['json']
            config_handler = 'json'
            config_extension = '.json'
    

    这将保持默认的config_files 列表不变,但使用.json 而不是.conf 来查找文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多