【问题标题】:Efficiently find all .zip files on an S3 bucket高效查找 S3 存储桶上的所有 .zip 文件
【发布时间】:2020-02-01 11:51:15
【问题描述】:

我有一堆 S3 存储桶,里面堆满了旧文件和档案(.zip 格式)。我想有效地查询一个存储桶并获取所有已压缩且大于 200MB 的文件的列表,然后将其删除。

所以我写了一些代码。它可以完成工作,但速度很慢。 S3 上的文件越多,API 调用越多,等待的时间就越长。对于包含 70 多个文件的存储桶,大约需要 50 秒才能确定,在这种情况下,需要 3 个 zip 文件。

#!/usr/bin/env python3.6
import boto3
from botocore.exceptions import ClientError


def find_all_zips(bucket: str) -> iter:
    print(f"Looking for .zip files on S3: {bucket} ...")
    b = boto3.resource("s3").Bucket(bucket)
    return (obj.key for obj in b.objects.all()
            if get_info(bucket=bucket, key=obj.key) is not None)


def get_info(bucket: str, key: str) -> str:
    s3 = boto3.client('s3')
    try:
        response = s3.head_object(Bucket=bucket, Key=key)
        has_size = response['ContentLength'] >= 209715200 # ~= 200MB in bytes
        if len(response['ContentType']) == 0:
            is_zip = False
        else:
            is_zip = response['ContentType'].split("/")[1] == 'zip'

        if has_size and is_zip:
            return key
    except ClientError as error:
        raise Exception(f"Failed to fetch file info for {key}: {error}")


if __name__ == "__main__":
    print(list(find_all_zips(bucket='MYBUCKET')))

我得到的输出是我所期望的:

Looking for .zip files on S3: MYBUCKET ...
['avocado-prices.zip', 'notepad.zip', 'spacerace.zip']

问题:有没有办法加快这件事?或者我应该启动一个数据库来记录我的 S3 文件及其类型?

【问题讨论】:

  • 代码从 lambda 函数运行?
  • 不,我在本地机器上运行它。
  • 考虑启用和查询 S3 库存报告。
  • 缓慢是由于网络和可能是您的互联网连接。你可以做的2件事。首先,尝试从 EC2 或 Lambda 运行您的代码。其次,在调用 head_object 检查大小之前使用密钥检查 zip 文件。这将减少您需要进行的 API 调用次数。

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


【解决方案1】:

如果您愿意使用文件名来识别 Zip 文件,则不需要额外调用 head_object()

import boto3

s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket('my_bucket')

max_size = 2 * 1024 * 1024

print(list(object.key for object in bucket.objects.all()
            if object.size >= max_size and object.key.endswith('.zip')))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2020-01-18
    • 2015-11-02
    • 1970-01-01
    相关资源
    最近更新 更多