[英]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.