如何在 Python 中使用 Boto3 庫透過 AWS 資源上傳物件到 S3?
問題陳述 − 使用 Python 中的 Boto3 庫將物件上傳到 S3。例如,如何將 test.zip 上傳到 S3 的 Bucket_1。
解決此問題的方法/演算法
步驟 1 − 匯入 boto3 和 botocore 異常來處理異常。
步驟 2 − 從 pathlib 匯入 PurePosixPath 來從路徑中檢索檔名。
步驟 3 − s3_path 和 filepath 是函式 upload_object_into_s3 中的兩個引數。
步驟 4 − 驗證 s3_path 是否以 AWS 格式傳遞,例如 s3://bucket_name/key,以及 filepath 是否為本地路徑,例如 C://users/filename。
步驟 5 − 使用 boto3 庫建立一個 AWS 會話。
步驟 6 − 為 S3 建立一個 AWS 資源。
步驟 7 − 分割 S3 路徑並執行操作以分離根儲存桶名稱和金鑰路徑。
步驟 8 − 獲取完整檔案路徑的檔名並新增到 S3 金鑰路徑中。
步驟 9 − 現在使用函式 upload_fileobj 將本地檔案上傳到 S3。
步驟 10 − 使用函式 wait_until_exists 等待操作完成。
步驟 11 − 根據響應程式碼處理異常,以驗證檔案是否已上傳。
步驟 12 − 如果在上傳檔案時出現問題,則處理通用異常。
示例
使用以下程式碼將檔案上傳到 AWS S3 −
import boto3 from botocore.exceptions import ClientError from pathlib import PurePosixPath def upload_object_into_s3(s3_path, filepath): if 's3://' in filepath: print('SourcePath is not a valid path.' + filepath) raise Exception('SourcePath is not a valid path.') elif s3_path.find('s3://') == -1: print('DestinationPath is not a s3 path.' + s3_path) raise Exception('DestinationPath is not a valid path.') session = boto3.session.Session() s3_resource = session.resource('s3') tokens = s3_path.split('/') target_key = "" if len(tokens) > 3: for tokn in range(3, len(tokens)): if tokn == 3: target_key += tokens[tokn] else: target_key += "/" + tokens[tokn] target_bucket_name = tokens[2] file_name = PurePosixPath(filepath).name if target_key != '': target_key.strip() key_path = target_key + "/" + file_name else: key_path = file_name print(("key_path: " + key_path, 'target_bucket: ' + target_bucket_name)) try: # uploading Entity from local path with open(filepath, "rb") as file: s3_resource.meta.client.upload_fileobj(file, target_bucket_name, key_path) try: s3_resource.Object(target_bucket_name, key_path).wait_until_exists() file.close() except ClientError as error: error_code = int(error.response['Error']['Code']) if error_code == 412 or error_code == 304: print("Object didn't Upload Successfully ", target_bucket_name) raise error return "Object Uploaded Successfully" except Exception as error: print("Error in upload object function of s3 helper: " + error.__str__()) raise error print(upload_object_into_s3('s3://Bucket_1/testfolder', 'c://test.zip'))
輸出
key_path:/testfolder/test.zip, target_bucket: Bucket_1 Object Uploaded Successfully
廣告