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

วิธีดึงรายละเอียด Ownership Control ของ S3 Bucket ด้วย Boto3 และ AWS Client


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

ใช้ไลบรารี Boto3 ใน Python เพื่อดึงรายละเอียด Ownership Control ของ S3 Bucket

ตัวอย่าง: หา Ownership Control Detail ของ Bucket_1 ใน S3

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

  1. ขั้นตอนที่ 1 – นำเข้า boto3 และ botocore.exceptions เพื่อจัดการข้อยกเว้น
  2. ขั้นตอนที่ 2 – ใช้ bucket_name เป็นพารามิเตอร์ในฟังก์ชัน
  3. ขั้นตอนที่ 3 – สร้าง AWS Session ด้วย Boto3
  4. ขั้นตอนที่ 4 – สร้าง AWS Client สำหรับ S3
  5. ขั้นตอนที่ 5 – ใช้ฟังก์ชัน get_bucket_ownership_controls ส่งชื่อ Bucket
  6. ขั้นตอนที่ 6 – คืนค่า Dictionary ที่มีรายละเอียดเกี่ยวกับ S3
  7. ขั้นตอนที่ 7 – จัดการข้อยกเว้นทั่วไปหากเกิดข้อผิดพลาดขณะลบไฟล์

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

ใช้โค้ดต่อไปนี้เพื่อดึง Ownership Detail ของ Bucket:

import boto3
from botocore.exceptions import ClientError

def get_bucket_ownership_control_of_s3(bucket_name):
    session = boto3.session.Session()
    s3_client = session.client('s3')
    try:
        result = s3_client.get_bucket_ownership_controls(Bucket=bucket_name)
    except ClientError as e:
        raise Exception("boto3 client error in get_bucket_ownership_control_of_s3: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in get_bucket_ownership_control_of_s3: " + e.__str__())
    return result

print(get_bucket_ownership_control_of_s3("Bucket_1"))

ผลลัพธ์

{
    'OwnershipControls': {
        'Rules': [
            {
                'ObjectOwnership': 'BucketOwnerPreferred'|'ObjectWriter'
            }
        ]
    }
}