如何使用 Python 中的 Boto3 库获取 AWS S3 中存在的存储桶列表?
boto3pythonserver side programmingprogramming
问题陈述 − 使用 Python 中的 boto3 库获取 AWS 中存在的所有存储桶列表。
示例 − 获取存储桶的名称,如 – BUCKET_1、BUCKET2、BUCKET_3
解决此问题的方法/算法
步骤 1 − 导入 boto3 和 botocore 异常来处理异常。
步骤 2 − 使用 Boto3 库创建 AWS 会话。
步骤 3 − 为 S3 创建 AWS 资源
步骤 4 −使用函数 buckets.all() 列出存储桶名称。
步骤 5 − 如果发生任何不必要的异常,则处理它
步骤 6 − 返回 buckets_namev列表
示例
以下代码获取 S3 中存在的存储桶列表 −
import boto3 from botocore.exceptions import ClientError # 使用 S3 资源获取 AWS 中存在的存储桶列表 def get_buckets_resource(): session = boto3.session.Session() # 用户也可以传递自定义访问密钥、secret_key 和令牌 s3_resource = session.resource('s3') try: buckets = list(s3_resource.buckets.all()) print("Got buckets using resource:", buckets) except ClientError: print("Couldn't get buckets.") raise else: return buckets get_buckets_resource()
输出
Got buckets using resource:[s3.Bucket(name='BUCKET_1'), s3.Bucket(name='BUCKET_2'), s3.Bucket(name='BUCKET_3)………… ]