Đề bài – Sử dụng thư viện boto3 trong Python để lấy cấu hình vòng đời của một bucket S3. Ví dụ: tìm lifecycle của Bucket_1 trong S3.
Phương pháp/Thuật toán giải quyết
Bước 1 – Import boto3 và các ngoại lệ từ botocore để xử lý lỗi.
Bước 2 – bucket_name là tham số trong hàm.
Bước 3 – Tạo phiên AWS (session) bằng thư viện boto3.
Bước 4 – Tạo client AWS cho dịch vụ S3.
Bước 5 – Gọi hàm get_bucket_lifecycle_configuration và truyền tên bucket.
Bước 6 – Hàm trả về một dictionary chứa thông tin chi tiết về bucket S3.
Bước 7 – Xử lý ngoại lệ chung nếu có lỗi xảy ra.
Ví dụ
Sử dụng mã sau để lấy vòng đời bucket:
import boto3
from botocore.exceptions import ClientError
def get_bucket_lifecycle_of_s3(bucket_name):
session = boto3.session.Session()
s3_client = session.client('s3')
try:
result = s3_client.get_bucket_lifecycle_configuration(Bucket=bucket_name)
except ClientError as e:
raise Exception("Lỗi client boto3 trong get_bucket_lifecycle_of_s3: " + e.__str__())
except Exception as e:
raise Exception("Lỗi không mong đợi trong hàm get_bucket_lifecycle_of_s3: " + e.__str__())
return result
print(get_bucket_lifecycle_of_s3("Bucket_1"))
Kết quả
{
'Rules': [
{
'ID': 'Rule for TaxDocs/',
'Prefix': 'TaxDocs',
'Status': 'Enabled',
'Transitions': [
{
'Days': 365,
'StorageClass': 'STANDARD_IA',
},
],
},
],
'ResponseMetadata': {
'...': '...',
},
}