【问题标题】:how to upload stream to AWS s3 with python如何使用 python 将流上传到 AWS s3
【发布时间】:2018-07-09 13:40:32
【问题描述】:

我想创建一个从 S3 获取 zip 文件(可能包含 csv 文件列表)的 lambda,将其解压缩并上传回 s3。 由于 lambda 受内存/磁盘大小的限制,我必须将它从 s3 流式传输并返回到它。 我使用python(boto3) 请参阅下面的代码

count = 0
obj = s3.Object( bucket_name, key )
buffer = io.BytesIO(obj.get()["Body"].read())
print (buffer)
z = zipfile.ZipFile(buffer)
for x in z.filelist:
    with z.open(x) as foo2:
        print(sys.getsizeof(foo2))
        line_counter = 0
        out_buffer = io.BytesIO()
        for f in foo2:
            out_buffer.write(f)
            # out_buffer.writelines(f)
            line_counter += 1
        print (line_counter)
        print foo2.name
        s3.Object( bucket_name, "output/"+foo2.name+"_output" ).upload_fileobj(out_buffer)
        out_buffer.close()
z.close()

结果是,在存储桶中创建了空文件。 例如:如果文件:input.zip 包含文件:1.csv,2.csv 我进入桶 2 具有相应名称的空 csv 文件。 另外,我不确定它是否确实流式传输文件,或者只是下载所有 zip 文件 谢谢

【问题讨论】:

  • 查看已编辑的问题
  • boto3 client.get_object() 方法支持 Range 参数。您可以使用它来请求一系列字节,例如“字节=1024-2048”。
  • @RELW 您可以使用 Python 将流上传到 AWS S3。请在下面查看我的答案

标签: python amazon-s3 lambda boto3 unzip


【解决方案1】:

上传前需要seek回到ByesIO文件的开头。

out_buffer = io.BytesIO()
for f in foo2:
    out_buffer.write(f)
    # out_buffer.writelines(f)
    line_counter += 1

out_buffer.seek(0) # Change stream position to beginning of file

s3.Object( bucket_name, "output/"+foo2.name+"_output").upload_fileobj(out_buffer)
out_buffer.close()

【讨论】:

    【解决方案2】:

    您可以将文件从 S3 解压缩并提取到 S3。

    s3Bucket ="s3-bucket"   #Provide S3 bucket name
    file_name = "test.zip"  #Provide zip file name
    
    s3=boto3.resource('s3')
    zip_obj = s3.Object(bucket_name=s3Bucket, key=file_name)
    buffer = BytesIO(zip_obj.get()["Body"].read())
    z = zipfile.ZipFile(buffer)
    for file in z.namelist():
        file_info = z.getinfo(file)
        s3.meta.client.upload_fileobj(
            z.open(file),
            Bucket=s3Bucket,
            Key=file,
            ExtraArgs={'ServerSideEncryption':'aws:kms','SSEKMSKeyId':'alias/<alias_name>'})
    

    参考 - https://github.com/vhvinod/ftp-to-s3/blob/master/extract-s3-to-s3.py

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 2020-04-02
      • 2016-03-14
      • 1970-01-01
      • 2021-05-18
      • 2018-07-07
      • 1970-01-01
      • 2020-12-23
      • 2018-01-19
      相关资源
      最近更新 更多