如何使用 Boto3 通过 AWS 客户端获取 S3 中存在的存储桶列表?

boto3pythonserver side programmingprogramming

问题陈述 − 使用 Python 中的 Boto3 库获取 AWS 中存在的所有存储桶列表

示例 − 获取存储桶的名称,如 – BUCKET_1、BUCKET2、BUCKET_3

解决此问题的方法/算法

步骤 1 − 导入 boto3 和 botocore 异常来处理异常。

步骤 2 − 使用 Boto3 库创建 AWS 会话。

步骤 3 − 为 S3 创建 AWS 客户端。

步骤 4 −使用函数 list_buckets() 将 bucket 的所有属性存储在字典中,如 ResponseMetadata、buckets

步骤 5 − 使用 for  循环从字典中仅获取 bucket 特定的详细信息,如名称、创建日期等。

步骤 6 − 现在,仅从 bucket 字典中检索 Name 并存储在列表中。

步骤 7 − 如果发生任何不必要的异常,请处理它

步骤 8 −返回 buckets_name 列表

示例

以下代码获取 S3 中存在的 bucket 列表 −

import boto3
from botocore.exceptions import ClientError

# 使用 S3 客户端获取 AWS 中存在的 bucket 列表
def get_buckets_client():
   session = boto3.session.Session()
   # 用户也可以传递自定义访问密钥、secret_key 和 token
   s3_client = session.client('s3')
   try:
      response = s3_client.list_buckets()
      buckets =[]
   for bucket in response['Buckets']
      buckets += {bucket["Name"]}

      except ClientError:
         print("Couldn't get buckets.")
         raise
      else:
         return buckets
print(get_buckets_client())

输出

['BUCKET_1', 'BUCKET_2', 'BUCKET_3'……..]

相关文章