如何创建zip文件并使用python boto3在S3中上传该文件[关闭]

问题描述 投票:0回答:3

如何创建zip文件并使用python boto3在S3中上传该文件。

我正在S3中上传文件,然后它将触发lambda函数/在lamdba函数中,我需要读取该文件并将其转换为文件Zip文件并将zip文件存储在同一s3存储桶中。

[请让我们知道如何做

python amazon-s3 zip boto3 uploading
3个回答
0
投票

这怎么办:

  1. Put的设置S3 Event Notifications,它将自动触发您的Lambda。

  2. 在lambda中获取对象,使用zipfile压缩它。

  3. 将压缩文件放入存储桶。

  4. 删除原始对象。

注意:该方案假定您的对象很小。否则,lambda内存和存储限制(最大3GB内存,500 MB磁盘空间)可能会使lambda不适合该任务。


0
投票
import boto3
import zipfile

ACCESS_KEY_ID = 'AKIAJXVYMCM2656GLRXA'
ACCESS_SECRET_KEY = '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'
BUCKET_NAME = 'dkatkuri-upload-file'    

def lambda_handler(event, context):
    s3 = boto3.client("s3")
    if event:
        print("Event:", event)
        file_obj = event["Records"][0]
        filename = str(file_obj['s3']['object']['key'])
        print("File Name:", filename)
        fileobj = s3.get_object(Bucket = "dkatkuri-upload-file", Key = filename)
        file_content = fileobj["Body"].read().decode('utf-8')
        my_zip = zipfile.ZipFile('stage.zip', 'w')
        file_write = my_zip.write(file_content)
        s3 = boto3.resource(
             's3',
             aws_access_key_id=ACCESS_KEY_ID,
            aws_secret_access_key=ACCESS_SECRET_KEY
    )
    s3_client.upload_file(file_write, BUCKET_NAME, 'stage.zip')
    print("Printed Dev File")
    my_zip.close()

    enter code here

    return 'Lambda Function'  

0
投票

我已添加上面的代码,但出现以下错误。请让我知道代码中的问题是什么。

[ERROR] OSError: [Errno 30] Read-only file system: 'stage.zip'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 17, in lambda_handler
    my_zip = zipfile.ZipFile('stage.zip', 'w')
  File "/var/lang/lib/python3.8/zipfile.py", line 1249, in __init__
    self.fp = io.open(file, filemode)
© www.soinside.com 2019 - 2024. All rights reserved.