如何使用 Boto3 和 AWS 客戶端獲取 S3 儲存桶的位置?


問題陳述 - 使用 Python 中的 boto3 庫獲取 S3 儲存桶的位置。例如,查詢 S3 中 Bucket_1 的位置。

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

步驟 1 - 匯入 boto3 和 botocore 異常以處理異常。

步驟 2 - 使用 bucket_name 作為函式中的引數。

步驟 3 - 使用 boto3 庫建立 AWS 會話。

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

步驟 5 - 現在使用函式 get_bucket_location_of_s3 並傳遞儲存桶名稱。

步驟 6 - 它返回包含有關 S3 詳細資訊的字典。

步驟 7 - 如果在刪除檔案時出現錯誤,請處理通用異常。

示例

使用以下程式碼獲取儲存桶位置 -

import boto3
from botocore.exceptions import ClientError

def get_bucket_location_of_s3(bucket_name):
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
      result = s3_client.get_bucket_location(Bucket=bucket_name,)
   except ClientError as e:
      raise Exception( "boto3 client error in get_bucket_location_of_s3: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in get_bucket_location_of_s3 function: " +    e.__str__())
   return result

print(get_bucket_location_of_s3("Bucket_1"))

輸出

{
   'LocationConstraint': 'us-west-2'|'us-west-1'|'us-east-2'|'us-east1',
   'ResponseMetadata': {
      '...': '...',
   },
}

更新於: 2021年3月22日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.