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

Cách dùng waiter bucket_not_exists kiểm tra bucket S3 không tồn tại bằng Boto3

Đề bài − Sử dụng thư viện boto3 trong Python để kiểm tra bucket không tồn tại dùng waiter. Ví dụ: dùng waiters kiểm tra Bucket_2 không tồn tại 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 − Tạo đối tượng wait cho bucket_not_exists bằng get_waiter.

Bước 6 − Dùng đối tượng wait để xác thực bucket không tồn tại. Mặc định kiểm tra mỗi 5 giây cho đến trạng thái thành công (bucket không có trong S3). Lỗi sau 20 lần thất bại. Người dùng có thể định nghĩa polling time và max attempts.

Bước 7 − Trả về None.

Bước 8 − Xử lý ngoại lệ chung nếu có lỗi khi kiểm tra bucket.

Ví dụ

Sử dụng code sau để dùng waiter kiểm tra bucket_not_exists:

import boto3
from botocore.exceptions import ClientError

def use_waiters_check_bucket_not_exists(bucket_name):
    session = boto3.session.Session()
    s3_client = session.client('s3')
    try:
        waiter = s3_client.get_waiter('bucket_not_exists')
        waiter.wait(Bucket=bucket_name,
                    WaiterConfig={'Delay': 2, 'MaxAttempts': 5})
        print('Bucket not exist: ' + bucket_name)
    except ClientError as e:
        raise Exception("boto3 client error in use_waiters_check_bucket_not_exists: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in use_waiters_check_bucket_not_exists: " + e.__str__())

print(use_waiters_check_bucket_not_exists("Bucket_2"))
print(use_waiters_check_bucket_not_exists("Bucket_1"))

Kết quả

Bucket not exist: Bucket_2
None
botocore.exceptions.WaiterError: Waiter BucketNotExists failed: Max attempts exceeded
"Unexpected error in use_waiters_check_bucket_not_exists: " + e.__str__())
Exception: Unexpected error in use_waiters_check_bucket_not_exists: Waiter BucketNotExists failed: Max attempts exceed

Đối với Bucket_2, kết quả là câu print và None. Vì response không trả về gì, nên in None.

Đối với Bucket_1, kết quả là ngoại lệ, vì bucket này tồn tại ngay cả sau max attempts kiểm tra.

Trong ngoại lệ, đọc được Max attempts exceeded.