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

วิธีใช้ Boto3 และ AWS Resource ตรวจสอบว่า Root Bucket มีอยู่ใน S3 หรือไม่


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

ใช้ Boto3 Library ใน Python เพื่อตรวจสอบว่า Root Bucket มีอยู่ใน S3 หรือไม่

ตัวอย่าง

Bucket_1 มีอยู่หรือไม่ใน S3

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

  1. ขั้นตอนที่ 1 – นำเข้า boto3 และ botocore.exceptions เพื่อจัดการข้อยกเว้น
  2. ขั้นตอนที่ 2 – สร้าง AWS Session ด้วย Boto3
  3. ขั้นตอนที่ 3 – สร้าง AWS Resource สำหรับ S3
  4. ขั้นตอนที่ 4 – ใช้ฟังก์ชัน head_bucket() จะคืนค่า 200 OK หาก Bucket มีอยู่และผู้ใช้มีสิทธิ์เข้าถึง มิฉะนั้น Response จะเป็น 403 Forbidden หรือ 404 Not Found
  5. ขั้นตอนที่ 5 – จัดการ Exception ตาม Response Code
  6. ขั้นตอนที่ 6 – คืนค่า True/False ตามว่า Bucket มีอยู่หรือไม่

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

โค้ดต่อไปนี้ตรวจสอบว่า Root Bucket มีอยู่ใน S3:

import boto3
from botocore.exceptions import ClientError

# To check whether root bucket exists or not
def bucket_exists(bucket_name):
    try:
        session = boto3.session.Session()
        # User can pass customized access key, secret_key and token as well
        s3_resource = session.resource('s3')
        s3_resource.meta.client.head_bucket(Bucket=bucket_name)
        print("Bucket exists.", bucket_name)
        exists = True
    except ClientError as error:
        error_code = int(error.response['Error']['Code'])
        if error_code == 403:
            print("Private Bucket. Forbidden Access! ", bucket_name)
        elif error_code == 404:
            print("Bucket Does Not Exist!", bucket_name)
        exists = False
    return exists

print(bucket_exists('bucket_1'))
print(bucket_exists('AWS_bucket_1'))

ผลลัพธ์

Bucket exists. bucket_1 True
Bucket Does Not Exist! AWS_bucket_1 False