如何捕获 botocore 的 NoSuchKey 异常?

我尝试编写“好”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"

但是 NoSuchKey 没有定义,我不能跟踪它到需要定义它的导入。

e.__class__botocore.errorfactory.NoSuchKey,但是 from botocore.errorfactory import NoSuchKey给出一个错误,而 from botocore.errorfactory import *也不工作,我不想捕获一个通用错误。

59170 次浏览
from botocore.exceptions import ClientError


try:
response = self.client.get_object(Bucket=bucket, Key=key)
return json.loads(response["Body"].read())
except ClientError as ex:
if ex.response['Error']['Code'] == 'NoSuchKey':
logger.info('No object found - returning empty')
return dict()
else:
raise

使用 botocore 1.5,似乎客户端句柄暴露了异常类:

session = botocore.session.get_session()
client = session.create_client('s3')
try:
client.get_object(Bucket=BUCKET, Key=FILE)
except client.exceptions.NoSuchKey as e:
print >> sys.stderr, "no such key in bucket"

在 boto3中,我能够访问 resource 的 meta 客户端中的异常。

import boto3


s3 = boto3.resource('s3')
s3_object = s3.Object(bucket_name, key)


try:
content = s3_object.get()['Body'].read().decode('utf-8')
except s3.meta.client.exceptions.NoSuchKey:
print("no such key in bucket")

我认为在 Boto3中最优雅的方法是

session = botocore.session.get_session()
client = session.create_client('s3')


try:
client.get_object(Bucket=BUCKET, Key=FILE)
except client.exceptions.NoSuchKey:
print("no such key in bucket")

关于错误处理的文档似乎很少,但下面列出了这样做的错误代码:

session = botocore.session.get_session()
client = session.create_client('s3')
try:
try:
client.get_object(Bucket=BUCKET, Key=FILE)
except client.exceptions.InvalidBucketName:
print("no such key in bucket")
except AttributeError as err:
print(err)

< botocore.errorfactory.S3Exceptions 对象在0x105e08c50 > 对象没有属性“ InvalidBucketName”。有效的例外是: BucketAlreadyExists,BucketAlreadyOwnedByYou,NoSuchBucket,NoSuchKey,NoSuchUpload,ObjectAlreadyInActiveTierError,ObjectNotInActiveTierError