How to use Boto3 to paginate through all tables present in AWS Glue


Problem Statement: Use boto3 library in Python to paginate through all tables from AWS Glue Data Catalog that is created in your account

Approach/Algorithm to solve this problem

  • Step 1: Import boto3 and botocore exceptions to handle exceptions.

  • Step 2: max_items, page_size and starting_token are the optional parameters for this function, while database_name is required.

    • max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination.

    • page_size denotes the size of each page.

    • starting_token helps to paginate, and it uses NextToken from a previous response.

  • Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.

  • Step 4: Create an AWS client for glue.

  • Step 5: Create a paginator object that contains details of all tables using get_tables

  • Step 5: Call the paginate function and pass the database_name as DatabaseName, max_items, page_size and starting_token as PaginationConfig

  • Step 6: It returns the number of records based on max_size and page_size.

  • Step 7: Handle the generic exception if something went wrong while paginating.

Example Code

Use the following code to paginate through all tables created in user account −

import boto3
from botocore.exceptions import ClientError

def paginate_through_tables(database_name, max_items=None:int,page_size=None:int, starting_token=None:string):
   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)

Output

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

Updated on: 15-Apr-2021

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements