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

วิธีใช้ Boto3 แบ่งหน้า (Paginate) ผ่าน Tables ทั้งหมดใน AWS Glue

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

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

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

  • ขั้นตอน 2: พารามิเตอร์: database_name (บังคับ), 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_tables

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

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

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

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

import boto3
from botocore.exceptions import ClientError

def paginate_through_tables(database_name, 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_tables')
        response = paginator.paginate(
            DatabaseName=database_name,
            PaginationConfig={
                'MaxItems': max_items,
                'PageSize': page_size,
                'StartingToken': starting_token
            }
        )
        return response
    except ClientError as e:
        raise Exception("boto3 client error in paginate_through_tables: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in paginate_through_tables: " + e.__str__())

a = paginate_through_tables("test_db", 2, 5)
print(*a)

ผลลัพธ์

{'TableList': [{'Name': 'temp_table', 'DatabaseName': 'test_db', 'Owner': 'abc', 'CreateTime': datetime.datetime(2020, 9, 10, 20, 44, 29, tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2020, 9, 10, 20, 44, 29, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(1970, 1, 1, 5, 30, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor': {'Columns': [{'Name': 'keyname', 'Type': 'string', 'Comment': ''}, {'Name': 'amount', 'Type': 'string', 'Comment': ''}, {'Name': 'effectivedate', 'Type': 'string', 'Comment': ''}, {'Name': 'clientname', 'Type': 'string', 'Comment': ''}, {'Name': 'accoutname', 'Type': 'varchar(5)', 'Comment': ''}, {'Name': 'clientid', 'Type': 'varchar(6)', 'Comment': ''}], 'Location': 's3://test/', 'InputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat', 'OutputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat', 'Compressed': False, 'NumberOfBuckets': 0, 'SerdeInfo': {'Name': 'test', 'SerializationLibrary': 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe', 'Parameters': {}}, 'BucketColumns': [], 'SortColumns': [], 'Parameters': {}, 'StoredAsSubDirectories': False}, 'PartitionKeys': [], 'ViewOriginalText': '', 'ViewExpandedText': '', 'TableType': 'EXTERNAL_TABLE', 'Parameters': {'EXTERNAL': 'TRUE', 'has_encrypted_data': 'false', 'parquet.compression': 'SNAPPY'}, 'CreatedBy': 'arn:aws:sts::782258485841:assumed-role/IVZ-ADFS-NorthBayLead/Hari.Porandla@invesco.com'}, {'Name': 'test_3', 'DatabaseName': 'test_db', 'Owner': 'abc', 'CreateTime': datetime.datetime(2020, 9, 10, 21, 54, 39, tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2020, 9, 10, 21, 54, 39, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(1970, 1, 1, 5, 30, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor': {'Columns': [{'Name': 'keyname', 'Type': 'string', 'Comment': ''}, {'Name': 'amount', 'Type': 'string', 'Comment': ''}, {'Name': 'effectivedate', 'Type': 'string', 'Comment': ''}, {'Name': 'clientname', 'Type': 'string', 'Comment': ''}, {'Name': 'accoutname', 'Type': 'varchar(5)', 'Comment': ''}, {'Name': 'clientid', 'Type': 'varchar(6)', 'Comment': ''}], 'Location': 's3://test3/', 'InputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat', 'OutputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat', 'Compressed': False, 'NumberOfBuckets': 0, 'SerdeInfo': {'Name': 'test_3', 'SerializationLibrary': 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe', 'Parameters': {}}, 'BucketColumns': [], 'SortColumns': [], 'Parameters': {}, 'StoredAsSubDirectories': False}, 'PartitionKeys': [], 'ViewOriginalText': '', 'ViewExpandedText': '', 'TableType': 'EXTERNAL_TABLE', 'CreatedBy': 'arn:aws:sts::***********:assumed-role/abc'}], 'ResponseMetadata': {'RequestId': 'dd35e6c5-*********************1', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 13:42:48 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '10301', 'connection': 'keep-alive', 'x-amzn-requestid': '*******************'}, 'RetryAttempts': 0}}

ผลลัพธ์รายละเอียด table รวมถึง: ชื่อ, database, เจ้าของ, เวลาสร้าง/อัปเดต, storage descriptor (columns, location, format, compression), partition keys, table type, parameters เป็นต้น