我只是选择python作为我的首选脚本语言,我试图找出如何使用boto3进行正确的错误处理.
我正在尝试创建一个IAM用户:
def create_user(username, iam_conn):
try:
user = iam_conn.create_user(UserName=username)
return user
except Exception as e:
return e
Run Code Online (Sandbox Code Playgroud)
当对create_user的调用成功时,我得到一个整洁的对象,其中包含API调用的http状态代码和新创建的用户的数据.
例:
{'ResponseMetadata':
{'HTTPStatusCode': 200,
'RequestId': 'omitted'
},
u'User': {u'Arn': 'arn:aws:iam::omitted:user/omitted',
u'CreateDate': datetime.datetime(2015, 10, 11, 17, 13, 5, 882000, tzinfo=tzutc()),
u'Path': '/',
u'UserId': 'omitted',
u'UserName': 'omitted'
}
}
Run Code Online (Sandbox Code Playgroud)
这非常有效.但是当这个失败时(比如用户已经存在),我只得到一个类型为botocore.exceptions.ClientError的对象,只有文本告诉我出了什么问题.
示例:ClientError('调用CreateUser操作时发生错误(EntityAlreadyExists):名称已省略的用户已存在.',)
这个(AFAIK)非常难以处理错误,因为我不能只打开生成的http状态代码(根据IAM的AWS API文档,用户已经存在409).这让我觉得我必须以错误的方式做事.最佳方式是boto3永远不会抛出异常,但juts总是返回一个反映API调用方式的对象.
任何人都可以在这个问题上启发我或指出我正确的方向吗?
非常感谢!
我正在尝试编写"好"的python并捕获S3没有这样的关键错误:
session = botocore.session.get_session()
client = session.create_client('s3')
try:
client.get_object(Bucket=BUCKET, Key=FILE)
except NoSuchKey as e:
print >> sys.stderr, "no such key in bucket"
Run Code Online (Sandbox Code Playgroud)
但NoSuchKey没有定义,我无法将其跟踪到我需要定义的导入.
e.__class__
是botocore.errorfactory.NoSuchKey
,但from botocore.errorfactory import NoSuchKey
给出了一个错误,from botocore.errorfactory import *
也不管用,我不希望捕捉一般错误.