Python yml profile只读

2024-10-03 15:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.yml文件,其结构如下:

logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter: DEBUG
mambu:
   connectiontimeout: 20000
   receivetimeout: 20000


---
spring:
  profiles: local
saraza:
  api:
    url: 'http://0.0.0.0'
    path: '/saraza'
---
spring:
  profiles: local2
saraza:
  api:
    url: 'http://0.0.0.2'
    path: '/saraza2'  

现在,我想做一个字典,只与配置文件'本地'提供的设置。我写了这个函数:

def app_config():
    """
    Returns app targets settings
    """
    with open('app.yml', 'r') as stream:
        documents = yaml.load_all(stream)

        # Keep only local profile
        settings =  [doc for doc in documents if doc['spring']['profiles'] == 'local'][0]
    return settings

但当它被执行时,我得到:

.0 = <generator object load_all at 0x7f0ff9383c50>

>   settings = [doc for doc in documents if doc['spring']['profiles'] == 'local'][0]
E   KeyError: 'spring'

conftest.py:21: KeyError

致以最诚挚的问候


Tags: pathapiapphttpurlstreamdocsettings
1条回答
网友
1楼 · 发布于 2024-10-03 15:34:15

-是一个document prefix,是YAML语法的正常部分。如果删除它,那么该文件中的多个文档将合并为一个,现在您有了重复的映射键。因为您正在读取一个包含多个文档的文件,所以应该使用yaml.load_all(),它将解析所有文档并在列表中返回它们。对文档列表的处理取决于用例的需要。你知道吗

相关问题 更多 >