【问题标题】:Parse .ini sections with python-decouple使用 python-decouple 解析 .ini 部分
【发布时间】:2017-06-06 16:00:17
【问题描述】:

Documentation 有一个范例,其中唯一的部分称为 settings 这似乎是 python-decouple 的默认命名空间,因此如果你有:

[settings]
DEBUG=True

您可以使用以下方式解析配置:

from decouple import config
DEBUG = config('DEBUG', default=False, cast=bool)  # no section argument

但是如果我们有自定义部分,例如:

[sectionA]
DEBUG=True

[sectionB]
foo="bar"

?

我知道可以轻松地使用 ConfigParser 来解析自定义部分,如下所示:

config_parser.get('sectionA', 'DEBUG')   # the corresponding call in ConfigParser

但我想知道它是如何通过 python-decouple 完成的,因为它还支持 .ini 文件

【问题讨论】:

    标签: python-3.x ini decoupling python-decouple


    【解决方案1】:

    部分似乎在code 中被硬编码为类属性,因此我认为对于这个问题没有任何干净的、参数化的解决方案。

    class RepositoryIni(RepositoryEmpty):
        """
        Retrieves option keys from .ini files.
        """
        SECTION = 'settings'
    
        def __init__(self, source):
            self.parser = ConfigParser()
            with open(source) as file_:
                self.parser.readfp(file_)
    
        def __contains__(self, key):
            return (key in os.environ or
                    self.parser.has_option(self.SECTION, key))
    
        def __getitem__(self, key):
            return self.parser.get(self.SECTION, key)
    

    【讨论】:

      猜你喜欢
      • 2011-09-18
      • 2016-04-10
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 2014-09-03
      相关资源
      最近更新 更多