我需要將 .txt- 檔案壓縮為 S3 位置上的 .gz,然后將其上傳到不同的 S3 存盤桶。我已經撰寫了以下代碼,但它沒有按預期作業:
def upload_gzipped(bucket, key, fp, compressed_fp=None, content_type='text/plain'):
with gzip.GzipFile(fileobj=compressed_fp, mode='wb') as gz:
shutil.copyfileobj(fp, gz)
compressed_fp.seek(0)
print(compressed_fp)
bucket.upload_fileobj(
compressed_fp,
key,
{'ContentType': content_type, 'ContentEncoding': 'gzip'})
source_bucket = event['Records'][0]['s3']['bucket']['name']
file_key_name = event['Records'][0]['s3']['object']['key']
response = s3.get_object(Bucket=source_bucket, Key=file_key_name)
original = BytesIO(response['Body'].read())
original.seek(0)
upload_gzipped(source_bucket, file_key_name, original)
有人可以在這里提供幫助,或者任何其他方法在 S3 位置上 gzip 檔案
uj5u.com熱心網友回復:
您似乎正在撰寫一個 AWS Lambda 函式。
一個更簡單的程式流程可能是:
- 下載檔案以
/tmp/使用s3_client.download_file() - 壓縮檔案
- 使用上傳檔案到 S3
s3.client_upload_file() - 洗掉里面的檔案
/tmp/
另外,請注意,AWS Lambda 函式可能會被呼叫,多個物件通過event. 但是,您的代碼目前僅處理帶有event['Records'][0]. 程式應該像這樣回圈遍歷這些記錄:
for record in event['Records']:
source_bucket = record['s3']['bucket']['name']
file_key_name = record['s3']['object']['key']
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/434233.html
標籤:python-3.x 亚马逊网络服务 亚马逊-s3 aws-lambda
上一篇:如何僅在我的網站中提供S3物件
