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

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


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

ใช้ไลบรารี Boto3 ใน Python เพื่อดึง Logging Details ของ S3 Bucket เช่น หา Logging Details ของ 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_logging ส่งชื่อ Bucket
  6. ขั้นตอนที่ 6 – คืนค่า Dictionary ที่มีรายละเอียดเกี่ยวกับ S3
  7. ขั้นตอนที่ 7 – จัดการข้อยกเว้นทั่วไปหากเกิดข้อผิดพลาดขณะลบไฟล์

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

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

import boto3
from botocore.exceptions import ClientError

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

print(get_bucket_logging_of_s3("Bucket_1"))

ผลลัพธ์

{
    'LoggingEnabled': {
        'TargetBucket': 'string',
        'TargetGrants': [
            {
                'Grantee': {
                    'DisplayName': 'string',
                    'EmailAddress': 'string',
                    'ID': 'string',
                    'Type': 'CanonicalUser'|'AmazonCustomerByEmail'|'Group',
                    'URI': 'string'
                },
                'Permission': 'FULL_CONTROL'|'READ'|'WRITE'
            }
        ],
        'TargetPrefix': 'string'
    }
}