AWS boto3如何从密钥中获取元数据?

adh*_*ari -1 metadata amazon-s3 amazon-web-services boto3

我正在尝试获取 s3 存储桶中上传的文件的元数据值

#我必须专门使用 boto3.resource('s3') 来进行项目中的其他 api 调用。

我在元数据字段下有以下可用数据

#元数据


Key=Content-Type
Value= application/json

Run Code Online (Sandbox Code Playgroud)

下面是代码

bucket= 'mybucket'
key='L1/input/file.json'
s3_resource = boto3.resource('s3')
object = s3_resource.Object(bucket,key)
metadata = object.metadata
Run Code Online (Sandbox Code Playgroud)

但我遇到了以下错误

[ERROR] ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden
Run Code Online (Sandbox Code Playgroud)

谁可以帮我这个事。

Joh*_*ein 5

注意你的语法。这行:

s3_client=boto3.resource('s3')
Run Code Online (Sandbox Code Playgroud)

正在返回 a resource,而不是 a client

因此,这一行失败了:

obj = s3_client.head_object(bucket,key)
Run Code Online (Sandbox Code Playgroud)

因为head_object()不是可以在 上执行的操作resource

相反,使用:

s3_resource = boto3.resource('s3')
object = s3_resource.Object('bucket_name','key')
metadata = object.metadata
Run Code Online (Sandbox Code Playgroud)

它将提供元数据字典。