如何使用 Boto3 遍歷 AWS Glue 中存在的 S3 儲存桶中的所有物件


問題陳述:在 Python 中使用boto3庫,從您帳戶中建立的 AWS Glue 資料目錄中的 S3 儲存桶遍歷所有物件。

解決此問題的方法/演算法

  • 步驟 1:匯入boto3botocore異常以處理異常。

  • 步驟 2:max_itemspage_sizestarting_token是此函式的可選引數,而bucket_name是必需引數。

    • max_items表示要返回的記錄總數。如果可用記錄數 > max_items,則響應中將提供NextToken以恢復分頁。

    • page_size表示每個頁面的大小。

    • starting_token有助於分頁,它使用先前響應中的最後一個鍵。

  • 步驟 3:使用boto3 庫建立 AWS 會話。確保在預設配置檔案中提到了region_name。如果沒有提到,則在建立會話時顯式傳遞region_name

  • 步驟 4:為 S3 建立 AWS 客戶端。

  • 步驟 5:建立一個paginator物件,其中包含使用list_objects的 S3 儲存桶的物件版本的詳細資訊。

  • 步驟 6:呼叫paginate函式並將max_itemspage_sizestarting_token作為PaginationConfig引數傳遞,同時將bucket_name作為Bucket引數傳遞。

  • 步驟 7:它根據max_sizepage_size返回記錄數。

  • 步驟 8:如果在分頁過程中出現錯誤,則處理通用異常。

程式碼示例

使用以下程式碼遍歷使用者帳戶中建立的 S3 儲存桶中的所有物件:

import boto3
from botocore.exceptions import ClientError

def paginate_through_all_objects_s3_bucket(bucket_name, max_items=None:int,page_size=None:int, starting_token=None:string):
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
   paginator = s3_client.get_paginator('list_objects')
      response = paginator.paginate(Bucket=bucket_name, PaginationConfig={
         'MaxItems':max_items,
         'PageSize':page_size,
         'StartingToken':starting_token}
      )
   return response
   except ClientError as e:
      raise Exception("boto3 client error in paginate_through_all_objects_s3_bucket: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in paginate_through_all_objects_s3_bucket: " + e.__str__())

#1st Run
a = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5)
print(*a)
#2nd Run
for items in a:
next_token = items['Contents'][max_items-1]['Key']
b = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5,next_token)
print(*b)

輸出

#1st Run
{'ResponseMetadata': {'RequestId': '5AE5VF7RK', 'HostId': **************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': **************', 'x-amz-request-id': '5AE5VF7RK', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': '',
'Contents': [{'Key': 'analytics-s3i/param.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '"e6f6b8e02"', 'Size': 1554, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************0'}}, {'Key': 'analytics-s3i/params.json', 'LastModified': datetime.datetime(2021, 3, 10, 20, 10, 47, tzinfo=tzutc()), 'ETag': '"22a4bf70c1ed2612"', 'Size': 1756, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}

#2nd Run
{'ResponseMetadata': {'RequestId': '5AEAWX', 'HostId': 'Uc********************************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': *****************************', 'x-amz-request-id': '5AEAWX', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': 'analytics-s3i/params.json',
'Contents': [{'Key': 'analytics-s3i/template.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '"3af411f"', 'Size': 21334, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}, {'Key': 'analytics-s3i2/param.json', 'LastModified': datetime.datetime(2020, 11, 20, 17, 32, 45, tzinfo=tzutc()), 'ETag': '"04c29cf86888f99"', 'Size': 1695, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}

更新於: 2021年4月16日

4K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.