2015-10-08 33 views
0

我试图从我的OpsWorks堆栈中使用python和boto3获取自定义json。获取名称是好的,但如果我想获得CustomJson - KeyError。不知道为什么。Python Boto3 OpsWorks KeyError通过获取CustomJson

import boto3 
import traceback 

client = boto3.client('opsworks') 

response = client.describe_stacks() 

max_elements = len(response['Stacks']) 

for i in range(max_elements): 
    stack_Name = response['Stacks'][i]['Name'] # works 

    try: 
     stack_CustomJson = response['Stacks'][i]['CustomJson'] # KeyError 
    except: 
     traceback.print_exc() 

这是控制台输出:

$ python3 get_custom_json.py 
Traceback (most recent call last): 
File "get_custom_json.py", line 27, in get_opsworks_details 
stack_CustomJson = response['Stacks'][i]['CustomJson'] 
KeyError: 'CustomJson' 

阅读从http://boto3.readthedocs.org/en/latest/reference/services/opsworks.html#OpsWorks.Client.describe_stacks的文档我没有看到“名称”和除了CustomJson“CustomJson”之间的区别是一个JSON对象。我必须改变它吗?

Thx提前

回答

0

与我公司的开发人员进行了一次快速聊天。得到了一些基本的介绍,以获得更好的编码和蟒蛇等等(必须放弃我的一些管理员的想法)。

不要迭代max_elements,更好地迭代'stack in stacks'之上。

for stack in response['Stacks']: 
    print(stack['CustomJson']) 

现在,它的工作原理 - 我将从OpsWorks堆栈中获得自定义json。但仍然存在KeyError。

Traceback (most recent call last): 
    File "get_custom_json.py", line 22, in <module> 
     get_opsworks_details() 
    File "get_custom_json.py", line 18, in get_opsworks_details 
     print(stack['CustomJson']) 
    KeyError: 'CustomJson' 

我会检查我是否可以再次找到他,看看为什么会发生这种情况。

[编辑]盲点 - 如果堆栈没有自定义json,则会发生KeyError。

1

偶尔会得到KeyError,因为响应中的CustomStack元素是可选的。如果为堆栈指定了自定义堆栈,它将被返回。否则,CustomStack密钥根本就不存在。你应该这样做:

if 'CustomStack' in stack: 
    # do your thing