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

Cách dùng Waiters kiểm tra bucket S3 tồn tại bằng Boto3 và AWS Client

Trong bài này, ta sẽ xem cách dùng thư viện Boto3 và chức năng Waiter để xác thực bucket S3 có tồn tại hay không. Ví dụ: dùng waiters kiểm tra Bucket_1 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_exists bằng get_waiter.

Bước 6 − Dùng đối tượng wait để xác thực bucket có tồn tại hay không. Mặc định kiểm tra mỗi 5 giây cho đến trạng thái thành công. 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_exists hay không:

import boto3
from botocore.exceptions import ClientError

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

print(use_waiters_check_bucket_exists("Bucket_1"))
print(use_waiters_check_bucket_exists("Bucket_2"))

Kết quả

Bucket exists: Bucket_1
None
botocore.exceptions.WaiterError: Waiter BucketExists failed: Max attempts exceeded
"Unexpected error in use_waiters_check_bucket_exists: " + e.__str__())
Exception: Unexpected error in use_waiters_check_bucket_exists: Waiter BucketExists failed: Max attempts exceed

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

Đối với Bucket_2, kết quả là ngoại lệ, vì bucket này không tồn tại.

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