Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách lấy chi tiết kiểm soát sở hữu bucket S3 bằng Boto3 và AWS Client

Đề bài − Sử dụng thư viện boto3 trong Python để lấy chi tiết kiểm soát sở hữu (ownership control) của bucket S3.

Ví dụ: tìm chi tiết kiểm soát sở hữu của Bucket_1 trong S3.

Cách tiếp cận/Thuật toán giải quyết

Bước 1 − Nhập boto3 và botocore exceptions để xử lý ngoại lệ.

Bước 2 − Dùng bucket_name làm tham số trong hàm.

Bước 3 − Tạo phiên AWS bằng boto3.

Bước 4 − Tạo client AWS cho S3.

Bước 5 − Dùng hàm get_bucket_ownership_controls và truyền tên bucket.

Bước 6 − Trả về dictionary chứa chi tiết về S3.

Bước 7 − Xử lý ngoại lệ chung nếu có lỗi khi xóa file.

Ví dụ

Sử dụng code sau để lấy chi tiết sở hữu bucket:

import boto3
from botocore.exceptions import ClientError

def get_bucket_ownership_control_of_s3(bucket_name):
    session = boto3.session.Session()
    s3_client = session.client('s3')
    try:
        result = s3_client.get_bucket_ownership_controls(Bucket=bucket_name)
    except ClientError as e:
        raise Exception("boto3 client error in get_bucket_ownership_control_of_s3: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in get_bucket_ownership_control_of_s3: " + e.__str__())
    return result

print(get_bucket_ownership_control_of_s3("Bucket_1"))

Kết quả

{
    'OwnershipControls': {
        'Rules': [
            {
                'ObjectOwnership': 'BucketOwnerPreferred'|'ObjectWriter'
            }
        ]
    }
}