我有一个带有此结构的.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'
现在,我想仅使用个人资料' local'提供的设置进行更正。我写了这个函数:
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
祝你好运
答案 0 :(得分:1)
---
是document prefix,它是YAML语法的正常部分。如果删除它,那么该文件中的多个文档将合并为一个,现在您有了重复的映射键。由于您正在阅读包含多个文档的文件,因此您应使用yaml.load_all()
来解析所有文档并将其返回列表中。您对该文档列表的处理取决于您的用例需求。