Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng Boto3 phân trang qua tất cả Table trong AWS Glue


Đề bài: Sử dụng thư viện boto3 trong Python để phân trang qua tất cả các Table (bảng) từ AWS Glue Data Catalog được tạo trong tài khoản của bạn.

Cách tiếp cận / Thuật toán

  • Bước 1: Import boto3 và botocore.exceptions để xử lý ngoại lệ.

  • Bước 2: max_items, page_size và starting_token là tham số tùy chọn, trong khi database_name là bắt buộc.

    • max_items chỉ định tổng số bản ghi trả về. Nếu số bản ghi có sẵn > max_items, một NextToken sẽ được cung cấp để tiếp tục phân trang.

    • page_size chỉ định kích thước mỗi trang.

    • starting_token giúp phân trang, sử dụng NextToken từ phản hồi trước.

  • Bước 3: Tạo phiên làm việc AWS bằng boto3. Đảm bảo region_name được cấu hình; nếu không, truyền rõ ràng.

  • Bước 4: Tạo client AWS cho dịch vụ glue.

  • Bước 5: Tạo đối tượng paginator chứa chi tiết tất cả Table bằng get_tables.

  • Bước 6: Gọi hàm paginate và truyền database_name như DatabaseName, max_items, page_size, starting_token như PaginationConfig.

  • Bước 7: Trả về số bản ghi dựa trên max_items và page_size.

  • Bước 8: Xử lý ngoại lệ chung nếu có lỗi khi phân trang.

Mã ví dụ

Sử dụng mã sau để phân trang qua tất cả Table:

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("Lỗi client boto3 trong paginate_through_tables: " + e.__str__())
    except Exception as e:
        raise Exception("Lỗi không mong muốn trong paginate_through_tables: " + e.__str__())

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

Kết quả

{'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}}