【问题标题】:Upload Gzip file using Boto3使用 Boto3 上传 Gzip 文件
【发布时间】:2019-08-16 11:48:16
【问题描述】:

我正在尝试将文件上传到 S3 之前我正在尝试 Gzip 文件,如果您看到下面的代码,上传到 S3 的文件大小没有变化,所以我想弄清楚我是否有错过了什么。

import gzip
import shutil
from io import BytesIO


def upload_gzipped(bucket, key, fp, compressed_fp=None, content_type='text/plain'):
    """Compress and upload the contents from fp to S3.

    If compressed_fp is None, the compression is performed in memory.
    """
    if not compressed_fp:
        compressed_fp = BytesIO()
    with gzip.GzipFile(fileobj=compressed_fp, mode='wb') as gz:
        shutil.copyfileobj(fp, gz)
    compressed_fp.seek(0)
    bucket.upload_fileobj(
        compressed_fp,
        key,
        {'ContentType': content_type, 'ContentEncoding': 'gzip'})

礼貌Link for the source

这就是我使用这个功能的方式,所以基本上从 SFTP 读取文件作为流,然后尝试 Gzip 压缩它们,然后将它们写入 S3。

with pysftp.Connection(host_name, username=user, password=password, cnopts=cnopts, port=int(port)) as sftp:
    list_of_files = sftp.listdir('{}{}'.format(base_path, file_path))
    is_file_found = False
    for file_name in list_of_files:
        if entity_name in str(file_name.lower()):
            is_file_found = True
            flo = BytesIO()
            # Step 1: Read File Using SFTP as input Stream
            sftp.getfo('{}{}/{}'.format(base_path, file_path, file_name), flo)
            s3_destination_key = '{}/{}'.format(s3_path, file_name)
            # Step 2: Write files to desitination S3
            logger.info('Moving file to S3 {} '.format(s3_destination_key))
            # Creating a bucket resource to use bucket object for file upload
            input_bucket_object = S3.Bucket(environment_config['S3_INBOX_BUCKET'])
            flo.seek(0)
            upload_gzipped(input_bucket_object, s3_destination_key, flo)

【问题讨论】:

  • 我测试了要点并且能够将正确的 gzip 压缩文件上传到 S3。但是,您的代码不完整,所以我不能说它是否有效。如果您能提供一个完整的测试用例来重现您的问题,我可能会提供更多帮助。

标签: python-3.x amazon-s3 gzip boto3


【解决方案1】:

upload_gzipped 函数似乎错误地使用了shutil.copyfileobj

查看https://docs.python.org/3/library/shutil.html#shutil.copyfileobj 表明您将源放在第一位,目标放在第二位。

此外,您只是将对象写入 gzip 压缩的对象,而没有实际压缩它。

您需要将fp 压缩成一个 Gzip 对象,然后将该特定对象上传到 S3。

我建议不要使用 github 上的那个要点,因为它似乎是错误的。

【讨论】:

  • 嗨巴蒂斯特。我从要点测试了源代码,它确实有效。 shutil.copyfileobj 调用将 gz 作为目标参数,因为这就是您使用 gzip.GzipFile 压缩的方式 - 您从未压缩的文件对象复制到 gz 文件对象。我不确定 OP 的问题是什么,因为他们的代码不完整(例如,它引用了未定义的变量,例如 entity_name)。
  • @DougRichardson:代码本身很好,除了占位符,问题主要围绕字节流压缩,或者你可以说在内存压缩中。
  • @noobie-php 在我的测试中 gzip 压缩有效。我用文本文件(压缩得很好)进行了测试。你测试的是什么类型的文件?
猜你喜欢
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
相关资源
最近更新 更多