Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Waiter Functionality สำหรับ bucket_not_exists ด้วย Boto3 และ AWS Client


ข้อกำหนดปัญหา

ใช้ไลบรารี Boto3 ใน Python เพื่อตรวจสอบว่า Bucket ไม่อยู่โดยใช้ Waiter Functionality เช่น ใช้ Waiter ตรวจสอบว่า Bucket_2 ไม่อยู่ใน S3

ขั้นตอนการแก้ปัญหา

  1. ขั้นตอนที่ 1 – นำเข้า boto3 และ botocore.exceptions เพื่อจัดการข้อยกเว้น
  2. ขั้นตอนที่ 2 – ใช้ bucket_name เป็นพารามิเตอร์ในฟังก์ชัน
  3. ขั้นตอนที่ 3 – สร้าง AWS Session ด้วย Boto3
  4. ขั้นตอนที่ 4 – สร้าง AWS Client สำหรับ S3
  5. ขั้นตอนที่ 5 – สร้าง Wait Object สำหรับ bucket_not_exists โดยใช้ get_waiter
  6. ขั้นตอนที่ 6 – ใช้ wait Object ตรวจสอบว่า Bucket ไม่อยู่ โดย Default จะตรวจสอบทุก 5 วินาทีจนถึงสถานะสำเร็จ (สถานะสำเร็จหมายถึง Bucket ไม่อยู่ใน S3) Error จะถูกคืนหลังจาก 20 ครั้งที่ล้มเหลว อย่างไรก็ตาม ผู้ใช้สามารถกำหนด Polling Time และ Max Attempts เองได้
  7. ขั้นตอนที่ 7 – คืนค่า None
  8. ขั้นตอนที่ 8 – จัดการข้อยกเว้นทั่วไปหากเกิดข้อผิดพลาดขณะตรวจสอบ Bucket

ตัวอย่างโค้ด

ใช้โค้ดต่อไปนี้เพื่อใช้ Waiter ตรวจสอบว่า 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"))

ผลลัพธ์

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

สำหรับ Bucket_2 ผลลัพธ์คือ Print Statement และ None เนื่องจาก Response ไม่คืนค่าอะไร จึงพิมพ์ None

สำหรับ Bucket_1 ผลลัพธ์คือ Exception เนื่องจาก Bucket นี้มีอยู่แม้หลังจาก Max Attempts ในการตรวจสอบ

ใน Exception สามารถอ่านได้ว่า Max attempts exceeded