【发布时间】: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'})
这就是我使用这个功能的方式,所以基本上从 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