如何使用 Boto3 和 AWS 客戶端來確定 S3 中是否存在根儲存桶?


問題陳述 - 使用 Python 中的 Boto3 庫來確定 S3 中是否存在根儲存桶。

示例 - 儲存桶 Bucket_1 是否存在於 S3 中。

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

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

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

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

步驟 4 - 使用函式 head_bucket()。如果儲存桶存在且使用者有權訪問它,則返回 200 OK。否則,響應將為 403 Forbidden404 Not Found

步驟 5 - 根據響應程式碼處理異常。

步驟 6 - 根據儲存桶是否存在返回 True/False。

示例

以下程式碼檢查 S3 中是否存在根儲存桶 -

import boto3
from botocore.exceptions import ClientError

# To check whether root bucket exists or not
def bucket_exists(bucket_name):
   try:
      session = boto3.session.Session()
      # User can pass customized access key, secret_key and token as well
      s3_client = session.client('s3')
      s3_client.head_bucket(Bucket=bucket_name)
      print("Bucket exists.", bucket_name)
      exists = True
   except ClientError as error:
      error_code = int(error.response['Error']['Code'])
      if error_code == 403:
         print("Private Bucket. Forbidden Access! ", bucket_name)
      elif error_code == 404:
         print("Bucket Does Not Exist!", bucket_name)
      exists = False
   return exists

print(bucket_exists('bucket_1'))
print(bucket_exists('AWS_bucket_1'))

輸出

Bucket exists. bucket_1
True
Bucket Does Not Exist! AWS_bucket_1
False

更新於: 2021年3月22日

409 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.