如何使用 boto3 即时提取 S3 中的文件? [英] How to extract files in S3 on the fly with boto3?

查看:40
本文介绍了如何使用 boto3 即时提取 S3 中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种在 S3 中即时提取 .gz 文件的方法,即无需将其下载到本地、提取然后将其推送回 S3.

I'm trying to find a way to extract .gz files in S3 on the fly, that is no need to download it to locally, extract and then push it back to S3.

使用 boto3 + lambda,我如何实现我的目标?

With boto3 + lambda, how can i achieve my goal?

我在 boto3 文档中没有看到任何提取部分.

I didn't see any extract part in boto3 document.

推荐答案

Amazon S3 是一项存储服务.没有内置的操作文件内容的功能.

Amazon S3 is a storage service. There is no in-built capability to manipulate the content of files.

但是,您可以使用 AWS Lambda 函数从 S3 检索对象,将其解压缩,然后再次上传内容备份.但请注意,Lambda 的临时磁盘空间有 500MB 的限制,因此请避免解压过多数据.

However, you could use an AWS Lambda function to retrieve an object from S3, unzip it, then upload content back up again. However, please note that there is limit of 500MB in temporary disk space for Lambda, so avoid unzipping too much data.

您可以将 S3 存储桶配置为在存储桶中创建新文件时触发 Lambda 函数.Lambda 函数将:

You could configure the S3 bucket to trigger the Lambda function when a new file is created in the bucket. The Lambda function would then:

  • 使用 boto3(假设您喜欢 Python)下载新文件
  • 使用zipfile Python 库提取文件
  • 使用 boto3 上传生成的文件
  • Use boto3 (assuming you like Python) to download the new file
  • Use the zipfile Python library to extract files
  • Use boto3 to upload the resulting file(s)

示例代码

import boto3

s3 = boto3.client('s3', use_ssl=False)
s3.upload_fileobj(
    Fileobj=gzip.GzipFile(
        None,
        'rb',
        fileobj=BytesIO(
            s3.get_object(Bucket=bucket, Key=gzip_key)['Body'].read())),
    Bucket=bucket,
    Key=uncompressed_key)

这篇关于如何使用 boto3 即时提取 S3 中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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