Python 如何捕获 botocore 的 NoSuchKey 异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42975609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:20:02  来源:igfitidea点击:

How to capture botocore's NoSuchKey exception?

pythonbotocore

提问by theist

I'm trying to write "good" python and capture a S3 no such key error with this:

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

But NoSuchKey isn't defined and I can't trace it to the import I need to have it defined.

但是 NoSuchKey 没有定义,我无法将它追溯到我需要定义它的导入。

e.__class__is botocore.errorfactory.NoSuchKeybut from botocore.errorfactory import NoSuchKeygives an error and from botocore.errorfactory import *doesn't work either and I don't want to capture a generic error.

e.__class__botocore.errorfactory.NoSuchKeyfrom botocore.errorfactory import NoSuchKey给出了错误并且from botocore.errorfactory import *也不起作用,我不想捕获一般错误。

回答by Jose Alban

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

回答by groner

Using botocore 1.5, it looks like the client handle exposes the exception classes:

使用 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"

回答by Randy

In boto3, I was able to access the exception in resource's meta client.

在 boto3 中,我能够访问资源的元客户端中的异常。

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")

回答by JeffSolo

I think the most elegant way to do this is in Boto3 is

我认为最优雅的方法是在 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")

The documentation on error handling seems sparse, but the following prints the error codes this works for:

关于错误处理的文档似乎很少,但以下打印了适用于的错误代码:

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 object at 0x105e08c50 > object has no attribute 'InvalidBucketName'. Valid exceptions are: BucketAlreadyExists, BucketAlreadyOwnedByYou, NoSuchBucket, NoSuchKey, NoSuchUpload, ObjectAlreadyInActiveTierError, ObjectNotInActiveTierError

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