如何使用Python中的Boto3库获取AWS S3中存在的桶列表?
问题陈述 - 使用Python中的boto3库获取AWS中所有存储桶的列表。
示例 - 获取像BUCKET_1,BUCKET2,BUCKET_3这样的存储桶名称。
更多Python相关文章,请阅读:Python 教程
解决此问题的方法/算法
步骤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和token
s3_resource = session.resource('s3')
try:
buckets = list(s3_resource.buckets.all())
print("使用资源获取到的存储桶:", buckets)
except ClientError:
print("无法获取存储桶。")
raise
else:
return buckets
get_buckets_resource()
输出
使用资源获取到的存储桶:[s3.Bucket(name='BUCKET_1'), s3.Bucket(name='BUCKET_2'), s3.Bucket(name='BUCKET_3)………… ]
极客教程