发生异常:“s3.ServiceResource”对象没有属性“head_object”

gkr*_*2d2 6 python amazon-s3 boto3

我正在检查 S3 存储桶中是否存在对象。以下是我正在使用的代码片段。 obj是文件名。

    s3 = boto3.resource('s3')
    try:
        s3.head_object(Bucket=bucket_name, Key=obj)
    except ClientError as e:
        return False
Run Code Online (Sandbox Code Playgroud)

但它抛出了我的异常:

An exception occurred in python_code : 's3.ServiceResource' object has no attribute 'head_object'

我用于此 API 的参考 - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.head_object

谁能帮我解决这个问题?

Ntw*_*ike 17

尝试:

s3 = boto3.client('s3')

代替

boto3.resource('s3')


Var*_*ngh 10

我在这里捆绑了一个详细的回复:

1. boto3.client("s3") will allow you to perform Low level API calls
2. boto3.resource('s3') will allow you to perform High level API calls
Run Code Online (Sandbox Code Playgroud)

在这里阅读:资源、客户端和会话之间 boto3 的区别?

您的要求/操作需要对存储桶而不是存储桶中的对象/资源执行操作。所以在这里,这是有道理的,这就是 AWS 人员在上述客户端方法中区分 API 调用包装器的方式

这就是为什么这里boto3.client("s3")出现的原因。


Nat*_*han 6

boto3 资源和客户端 API 不同。由于实例化了一个boto3.resource("s3")对象,因此必须使用该对象可用的方法。head_object()不可用于,resource但可用于client。其他答案提供了详细信息,如果您切换到使用clientAPI,则可以如何使用该head_object()方法。如果您在代码库的其余部分中使用resourceAPI,请注意您可以检查存储桶中是否存在项目,只是做法略有不同。Boto3 文档中给出的示例是:

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
for obj in bucket.objects.all():
    print(obj.key)  # Change this to check membership, etc.
Run Code Online (Sandbox Code Playgroud)

为什么使用resource()?您无需进行第二次 API 调用即可获取对象!它们可以作为存储桶中的集合提供给您(通过buckets.objects)。