gpt4 book ai didi

python - 如何使用循环直到将键添加到字典中?

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:49 25 4
gpt4 key购买 nike

我使用 Django 作为框架。我正在使用 boto3 在我的 View 函数中创建一个 AWS 帐户。每个创建的 aws 账户都会有一个 AccountId。在讨论更多细节之前,这是我的代码片段:

 org = boto3.client('organizations')
acc = org.create_account(
Email=email,
AccountName=lab_name,
IamUserAccessToBilling='ALLOW'
)
cid = acc['CreateAccountStatus']['Id']
time.sleep(70)

#GET ACCOUNT DETAILS
status = org.describe_create_account_status(
CreateAccountRequestId=cid
)
accid = status['CreateAccountStatus']['AccountId']

最初我正在创建帐户。正如我之前提到的,创建帐户需要一些时间(大约 1 到 1.5 分钟)。然后我需要获取帐户详细信息,其中之一是 AccountId。我尝试增加 sleep 时间来解决这个问题,但这没有帮助。当我尝试获取“accid”声明行中的 AccountId 值时,出现错误。我收到的错误是:

KeyError: AccountId doesn't exist

发生这种情况可能是因为帐户尚未创建,并且在该事件之前我的代码正在尝试获取 AccountId 值。那么如何获取AccountId值呢?我应该尝试将其放入循环中还是使用 try 和 except block 来避免错误消息?请帮忙。提前致谢。

最佳答案

 status = org.describe_create_account_status(CreateAccountRequestId=cid)

while status.get('CreateAccountStatus',{}).get('AccountId',None) is None:
# sleep here
status = org.describe_create_account_status(CreateAccountRequestId=cid)

accid = status['CreateAccountStatus']['AccountId']

这将使用 dict.get(key, default) 提供它(或空的 dict) 'CreateAccountStatus''AccountId'None 并在其为 None 时循环。

关于dict.get()dict.get-API

<小时/>

正如 JonClements 所指出的,为此使用 while True: ... break ... 结构可能更Pythonic:

while True:
status = org.describe_create_account_status(CreateAccountRequestId=cid)
try:
accid = status['CreateAccountStatus']['AccountId']
break
except KeyError:
time.sleep(30)

这避免了 status = ... 行的重复,并使流程更加清晰。

使用 try: ... except: 更适合 pythonic ask-forgiveness-not-permission方法。

关于python - 如何使用循环直到将键添加到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48822642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com