如何使用 Boto3 和 AWS 客户端确定 S3 中是否存在根存储桶?

boto3pythonserver side programmingprogramming

问题陈述 − 使用 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

# 检查根存储桶是否存在
def bucket_exists(bucket_name):
   try:
      session = boto3.session.Session()
      # 用户也可以传递自定义的访问密钥、secret_key 和 token
      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

相关文章