Python 如何使用Boto3来分页浏览AWS Glue中存在的所有表格
问题陈述:使用Python中的 boto3 库来分页浏览由您的账户创建在AWS Glue数据目录中的所有表格。
阅读更多:Python 教程
解决此问题的方法/算法
- 步骤1: 导入 boto3 和 botocore 异常以处理异常情况。
-
步骤2: 这个函数的可选参数有 max_items 、 page_size 和 starting_token ,但是需要指定 database_name 。
- max_items 表示要返回的记录总数。如果可用的记录数> max_items ,则响应中将提供 NextToken 以继续使用分页。
-
page_size 表示每个页面的大小。
-
starting_token 用于分页,它使用先前响应中的 NextToken 。
-
步骤3: 使用 boto3 创建AWS会话。确保在默认配置文件中指定了 region_name 。如果没有指定,则在创建会话时显式传递 region_name 。
-
步骤4: 为Glue创建一个AWS客户端。
-
步骤5: 创建一个包含详情的 paginator 对象,使用get_tables获取所有表格的信息。
-
步骤6: 调用 paginate 函数,并将 database_name 指定为 DatabaseName , max_items 、 page_size 和 starting_token 分别指定为 PaginationConfig
-
步骤7: 如果在分页时发生错误,请处理通用异常。
示例代码
使用以下代码分页浏览用户账户中创建的所有表格-
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)
输出
{'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}}
极客教程