使用 python-decouple 解析 .ini 部分

Parse .ini sections with python-decouple

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 文件

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

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)