【问题标题】:save a zip file downloaded in AWS EC2 to a gzip file in S3, using python boto3 in memory使用内存中的 python boto3 将在 AWS EC2 中下载的 zip 文件保存到 S3 中的 gzip 文件
【发布时间】:2022-10-14 18:51:47
【问题描述】:

我很欣赏这个问题非常具体,但我认为这应该是一个常见问题。我已经解决了部分问题,但没有解决整个链条。

输入: 在 AWS EC2 实例中,我下载了一个zip压缩的来自互联网的文件

输出: 我保存gzip 压缩文件到 S3 存储桶

我看到了两种方法:

  1. 在 EC2 中保存临时文件,然后将它们复制到 S3
  2. 在EC2中转换内存中的数据,并直接保存到S3

    我知道怎么做第一个选项,但是由于资源限制,并且因为我需要下载很多文件,我想尝试第二个选项。这是我到目前为止所拥有的:

    import requests, boto3, gzip
    
    zip_data = requests.get(url).content
    
    #I can save a temp zip file in EC2 like this, but I would like to avoid it
    with open(zip_temp, 'wb') as w:    
        w.write(zip_data)
    
    #missing line that decompresses the zipped file in memory and returns a byte-object, I think?
    #like: data = SOMETHING (zip_data)
    
    gz_data = gzip.compress(data)
    
    client = boto3.client('s3')
    output = client.put_object( 
            Bucket = 'my-bucket',
            Body = gz_data,
            Key = filename)
    

    此外,在决定选择哪个选项时,我是否应该考虑任何一般性考虑?

【问题讨论】:

    标签: python zip boto3 gzip


    【解决方案1】:

    事实证明这很简单:

    import requests, boto3, gzip
    from zipfile import ZipFile
    from io import BytesIO
    
    zip_data = requests.get(url).content
    
    with ZipFile(BytesIO(zip_data)) as myzip:
    
        with myzip.open('zip_file_inside.csv') as mycsv:
    
            gz_data = gzip.compress(mycsv.read())
    
            client = boto3.client('s3')
    
            output = client.put_object( 
                Bucket = 'my-bucket',
                Body = gz_data,
                Key = filename)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2017-05-22
      • 2016-01-12
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2015-06-05
      相关资源
      最近更新 更多