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

วิธีใช้ Boto3 แบ่งหน้า (Paginate) ผ่าน Security Configurations ใน AWS Glue

ข้อกำหนดปัญหา: ใช้ไลบรารี boto3 ใน Python เพื่อแบ่งหน้าผ่าน security configurations จาก AWS Glue Data Catalog

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

  • ขั้นตอน 1: นำเข้า boto3 และ botocore.exceptions

  • ขั้นตอน 2: พารามิเตอร์เลือกได้: max_items, page_size, starting_token

    • max_items: จำนวนระเบียนสูงสุด
    • page_size: ขนาดแต่ละหน้า
    • starting_token: ใช้ NextToken จาก response ก่อนหน้า

  • ขั้นตอน 3: สร้าง AWS session ด้วย boto3 พร้อมระบุ region_name

  • ขั้นตอน 4: สร้าง AWS client สำหรับ glue

  • ขั้นตอน 5: สร้าง paginator object ด้วย get_security_configurations (แก้จาก get_security_configuration ตัวเดี่ยว)

  • ขั้นตอน 6: เรียก paginate พร้อมส่ง PaginationConfig

  • ขั้นตอน 7: คืนค่าระเบียนตาม max_items และ page_size

  • ขั้นตอน 8: จัดการข้อยกเว้นทั่วไป

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

import boto3
from botocore.exceptions import ClientError

def paginate_through_security_configuration(max_items=None, page_size=None, starting_token=None):
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        paginator = glue_client.get_paginator('get_security_configurations')
        response = paginator.paginate(
            PaginationConfig={
                'MaxItems': max_items,
                'PageSize': page_size,
                'StartingToken': starting_token
            }
        )
        return response
    except ClientError as e:
        raise Exception("boto3 client error in paginate_through_security_configuration: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in paginate_through_security_configuration: " + e.__str__())

a = paginate_through_security_configuration(2, 5)
print(*a)

ผลลัพธ์

{'SecurityConfigurations': [{'Name': 'test-sc', 'CreatedTimeStamp': datetime.datetime(2020, 9, 24, 1, 53, 21, 265000, tzinfo=tzlocal()), 'EncryptionConfiguration': {'S3Encryption': [{'S3EncryptionMode': 'SSE-KMS', 'KmsKeyArn': 'arn:aws:kms:us-east-1:*************:key/***************'}]}}, {'Name': 'port-sc', 'CreatedTimeStamp': datetime.datetime(2020, 11, 6, 0, 38, 3, 753000, tzinfo=tzlocal()), 'EncryptionConfiguration': {'S3Encryption': [{'S3EncryptionMode': 'SSE-KMS', 'KmsKeyArn': 'arn:aws:kms:us-east-1:********:key/***************'}}]}, 'NextToken': '', 'ResponseMetadata': {'RequestId': '**********', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 13:19:57 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '826', 'connection': 'keep-alive', 'x-amzn-requestid': '*********'}, 'RetryAttempts': 0}}

หมายเหตุ: API ที่ถูกต้องคือ get_security_configurations (พหูพจน์) ไม่ใช่ get_security_configuration — โค้ดข้างต้นได้แก้ไขแล้ว Security Configuration ใน Glue ใช้สำหรับกำหนดการเข้ารหัสข้อมูล (S3 encryption, CloudWatch encryption, Job bookmarks encryption)