首页 > 解决方案 > Boto3 无法从名称中包含时间戳的文件中读取元数据

问题描述

我正在尝试使用 boto3 从 s3 存储桶中读取文件中附加的元数据内容

key = "myfile_20401__2021-03-04_16:33:12.597"
aws_s3_client=boto3.client("s3")

def get_s3_metadata(key):
    bucket="my_bucket_name"
    s3_client=aws_s3_client()
    s3_response = s3_client.get_object(Bucket=bucket, Key=key)
    metadata = s3_response.get("Metadata")


get_s3_metadata(key)

但是上面的代码返回以下错误

[ERROR] ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
File "/var/runtime/botocore/client.py", line 386, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 705, in _make_api_call
    raise error_class(parsed_response, operation_name)

经分析,这不是由于访问问题引起的,而是由于文件名引起的。所以当我从文件中删除时间戳时,它就可以工作了。

那么有什么方法可以在不更改文件名(包括时间戳)的情况下解决这个问题?是否有人可以提供帮助?

标签: python-3.xamazon-s3boto3

解决方案


您的 S3 对象键包含字符(冒号),与 S3 一起使用是不安全的。幸运的是,这很容易解决,因为要使用冒号,您只需对它们进行 urlencode:

from urllib.parse import quote
import boto3


def get_s3_metadata(key):
    bucket="my_bucket_name"
    s3_client=boto3.client("s3")
    s3_response = s3_client.get_object(Bucket=bucket, Key=quote(key))
    metadata = s3_response.get("Metadata")

    
key = "myfile_20401__2021-03-04_16:33:12.597"
get_s3_metadata(key)


推荐阅读