如何使用 lambda 和 python 在 s3 上压缩文件 [英] How to zip files on s3 using lambda and python

查看:45
本文介绍了如何使用 lambda 和 python 在 s3 上压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存档 s3 上存在的多个文件,然后将存档上传回 s3.我正在尝试使用 lambda 和 python.由于某些文件的大小超过 500MB,因此无法在/tmp"中下载.有什么办法可以将文件一个一个地流式传输并存档?

I need to archive multiply files that exists on s3 and then upload the archive back to s3. I am trying to use lambda and python. As some of the files have more than 500MB, downloading in the '/tmp' is not an option. Is there any way to stream files one by one and put them in archive?

推荐答案

不要写入磁盘,与 S3 之间进行流式传输

Do not write to disk, stream to and from S3

从源存储桶流式传输 Zip 文件,并使用 Python 将其内容即时读写回另一个 S3 存储桶.

Stream the Zip file from the source bucket and read and write its contents on the fly using Python back to another S3 bucket.

此方法不会占用磁盘空间,因此不受大小限制.

This method does not use up disk space and therefore is not limited by size.

基本步骤是:

  • 使用 Boto3 S3 资源对象将 S3 中的 zip 文件读取到 BytesIO 缓冲区对象中
  • 使用 zipfile 模块打开对象
  • 使用名称列表方法遍历 zip 文件中的每个文件
  • 使用资源 meta.client.upload_fileobj 方法将文件写回 S3 中的另一个存储桶

代码使用 Boto3 的 Python 3.6

The Code Python 3.6 using Boto3

s3_resource = boto3.resource('s3')
zip_obj = s3_resource.Object(bucket_name="bucket_name_here", key=zip_key)
buffer = BytesIO(zip_obj.get()["Body"].read())

z = zipfile.ZipFile(buffer)
for filename in z.namelist():
    file_info = z.getinfo(filename)
    s3_resource.meta.client.upload_fileobj(
        z.open(filename),
        Bucket=bucket,
        Key=f'{filename}'
    )

注意:AWS 执行时间限制最长为 15 分钟,所以您能在这段时间内处理您的巨大文件吗?只有通过测试才能知道.

Note: AWS Execution time limit has a maximum of 15 minutes so can you process your HUGE files in this amount of time? You can only know by testing.

这篇关于如何使用 lambda 和 python 在 s3 上压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆