【问题标题】:Is there a way to make ListObjectsV2 to validate s3 object type/extension?有没有办法让 ListObjectsV2 验证 s3 对象类型/扩展?
【发布时间】:2021-12-20 17:41:28
【问题描述】:

我正在 python3 中使用 ListObjectsV2 检查 s3 位置是否存在。

我有一个需要验证 s3 对象的文件类型或扩展名的用例。

import boto3
s3 = boto3.client("s3")
bucket="bucketName"
key="folder1/folder2/myObject.csv"
res = s3.list_objects_v2(Bucket=bucket, Prefix=key)
print(res)
print(res.get("KeyCount"))
if res.get("KeyCount") > 0: print("s3 object exists")
else: print("s3 object does not exists")

示例对象如下: s3://bucketName/folder1/folder2/myObject.csv

以下给出输出的场景:

  1. s3://bucketName/folder1/folder2/myObject.csv 给出“s3 对象存在”
  2. s3://bucketName/folder1/folder2/myObject.c 给出“s3 对象存在”
  3. s3://bucketName/folder1/folder2/myObject。给出“s3 对象存在”
  4. s3://bucketName/folder1/folder2/myObject.x 给出“s3 对象不存在”

我观察到部分扩展也在验证中。

我也想要 2,3 作为“s3 对象不存在”。我可能有很多扩展名,所以不能使用“以”结尾。 也许我可以尝试使用在“。”之后划分 s3path 的解析器。用于扩展和使用 with 结束。但我正在寻找更简单的方法。

提前致谢。

【问题讨论】:

    标签: amazon-web-services amazon-s3 boto3 python-3.8


    【解决方案1】:

    ListObject "将响应限制为以指定前缀开头的键。"这正是您所看到的,因为“folder1/folder2/myObject.csv”以“folder1/folder2/myObject”开头。

    如果您想查看一个对象是否存在,您需要一个对特定对象进行操作的 API。一种这样的选择是调用HeadObject 并查看它是否因无效密钥而失败:

    import botocore.exceptions
    
    def does_key_exist(s3, bucket, key):
        try:
            # Try to head the object
            s3.head_object(Bucket=bucket, Key=key)
            # All good
            return True
        except botocore.exceptions.ClientError as e:
            # See if the failure is because the object doesn't exist
            code = e.response['Error']['Code']
            if code == "NoSuchKey" or code == "404":
                return False
            else:
                # Some other error, let the caller handle it if they want
                raise
    

    【讨论】:

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