【问题标题】:Boto3 unable to read the metadata from the file which contains timestamp in the nameBoto3 无法从名称中包含时间戳的文件中读取元数据
【发布时间】:2021-12-11 02:15:32
【问题描述】:

我正在尝试使用 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)

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

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

【问题讨论】:

  • 尝试key = "myfile_20401__2021-03-04_16:33:12.597" - 如果那是您的确切代码,您的密钥可能已被切断
  • 您能否编辑您的帖子以包含minimal reproducible example?就像现在一样,这是一个语法错误。
  • 嗨@ErmiyaEskandary 和Anon,我已经以可以在真实场景中重现的方式更新了代码——(在这种情况下,当aws lambda 附加了s3 触发器时)。我尝试了与提到的相同的方式-key =“myfile_20401__2021-03-04_16:33:12.597”,但重新调整了相同的错误。那么这是否意味着 boto3 不支持从此类文件名中读取元数据?

标签: python-3.x amazon-s3 boto3


【解决方案1】:

您的 S3 对象密钥包含字符(冒号),即aren't safe for use with 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多