如何使用 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.