[英]Upload Gzip file using Boto3
我尝试将文件上传到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'})
礼节链接的来源
这就是我使用此功能的方式,因此基本上是从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)
似乎upload_gzipped
函数使用shutil.copyfileobj
不正确的shutil.copyfileobj
。
查看https://docs.python.org/3/library/shutil.html#shutil.copyfileobj显示您将源放在第一位,目标放在第二位。
另外,您只是将对象写入压缩的对象,而无需实际对其进行压缩。
您需要将fp
压缩为Gzip对象,然后将该特定对象上载到S3。
我建议不要使用来自github的要点,因为它似乎是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.