如何使用 Boto3 通过 AWS 客户端获取 S3 中存在的存储桶列表?
问题陈述 - 在 Python 中使用 Boto3 库获取 AWS 中所有存在的存储桶列表
示例 - 获取存储桶名称,例如 - BUCKET_1、BUCKET2、BUCKET_3
解决此问题的方法/算法
步骤 1 - 导入 boto3 和 botocore 异常以处理异常。
步骤 2 - 使用 Boto3 库创建 AWS 会话。
步骤 3 - 为 S3 创建 AWS 客户端。
步骤 4 - 使用函数 list_buckets() 将存储桶的所有属性存储在字典中,例如 ResponseMetadata、buckets
步骤 5 - 使用for 循环从字典中获取仅与存储桶相关的详细信息,例如名称、创建时间等。
步骤 6 - 现在,仅从存储桶字典中检索名称并存储在列表中。
步骤 7 - 如果发生任何不需要的异常,则进行处理
步骤 8 - 返回存储桶名称列表
示例
以下代码获取 S3 中存在的存储桶列表 -
import boto3
from botocore.exceptions import ClientError
# To get list of buckets present in AWS using S3 client
def get_buckets_client():
session = boto3.session.Session()
# User can pass customized access key, secret_key and token as well
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'……..]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP