1

文档有一个范例,其中唯一的部分称为设置 这似乎是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文件

4

1 回答 1

0

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

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)
于 2018-01-04T12:30:50.473 回答