คำชี้แจงปัญหา − ใช้ไลบรารี Boto3 ใน Python เพื่อตรวจสอบว่ามีที่ฝากข้อมูลรูทอยู่ใน S3 หรือไม่
ตัวอย่าง − Bucket_1 มีหรือไม่มีใน S3
แนวทาง/อัลกอริทึมในการแก้ปัญหานี้
ขั้นตอนที่ 1 - นำเข้าข้อยกเว้น boto3 และ botocore เพื่อจัดการกับข้อยกเว้น
ขั้นตอนที่ 2 − สร้างเซสชัน AWS โดยใช้ไลบรารี boto3
ขั้นตอนที่ 3 − สร้างทรัพยากร AWS สำหรับ S3
ขั้นตอนที่ 4 − ใช้ฟังก์ชัน head_bucket() . ส่งคืน 200 ตกลง หากมีที่ฝากข้อมูลและผู้ใช้มีสิทธิ์เข้าถึง มิฉะนั้น คำตอบจะเป็น 403 Forbidden หรือ 404 ไม่พบ .
ขั้นตอนที่ 5 − จัดการข้อยกเว้นตามรหัสตอบกลับ
ขั้นตอนที่ 6 − คืนค่า True/False ขึ้นอยู่กับว่ามีที่ฝากข้อมูลหรือไม่
ตัวอย่าง
รหัสต่อไปนี้ตรวจสอบว่ามีที่ฝากข้อมูลรูทอยู่ใน 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