如何使用 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