Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Boto3를 사용하여 AWS Glue 데이터 카탈로그에서 데이터베이스의 테이블 정의를 가져오는 방법

<시간/>

사용자가 AWS Glue Data Catalog에서 데이터베이스의 정규식에 따라 일치하는 모든 테이블 또는 일부 테이블의 정의를 검색하는 방법을 살펴보겠습니다.

데이터베이스 'QA-테스트'의 모든 테이블에 대한 테이블 정의 검색 '보안'으로 표 및 '직원' .

이 문제를 해결하기 위한 접근 방식/알고리즘

  • 1단계: boto3 가져오기 및 보토코어 예외를 처리하기 위한 예외.

  • 2단계: database_name regular_expression_for_table_name 동안 필수 매개변수입니다. 선택적 매개변수입니다. 사용자가 모든 테이블의 세부 정보를 가져오려는 경우 정규식을 제공할 필요가 없습니다. 그러나 제한된 테이블만 가져와야 하는 경우 정규식이 필요합니다. 정규식을 제대로 작성하지 않으면 결과가 변경될 수 있으므로 주의하여 작성하십시오.

  • 3단계: boto3 lib를 사용하여 AWS 세션 생성 . region_name을(를) 확인하십시오. 기본 프로필에 언급되어 있습니다. 언급되지 않은 경우 세션을 생성하는 동안 region_name을 명시적으로 전달하십시오.

  • 4단계: 글루용 AWS 클라이언트 생성 .

  • 5단계: 이제 get_tables 함수를 사용하고 database_name을 전달합니다. DatabaseName 및 regular_expression_for_table_name으로 표현식 매개변수로.

  • 6단계: 주어진 데이터베이스에서 모든 또는 일치하는 테이블의 정의를 반환합니다.

  • 7단계: 작업을 확인하는 동안 문제가 발생한 경우 일반 예외를 처리합니다.

예시 코드

다음 코드는 주어진 데이터베이스에서 모든 테이블 정의를 검색합니다 -

import boto3
from botocore.exceptions import ClientError

def retrieves_tables_detail(database_name, regular_expression_for_table_name=None)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.get_tables(DatabaseName = database_name, Expression=regular_expression_for_table_name)                        
      return response
   except ClientError as e:
      raise Exception(
         "boto3 client error in retrieves_tables_detail: " + e.__str__())
   except Exception as e:
      raise Exception(
         "Unexpected error in retrieves_tables_detail: " + e.__str__())
print(retrieves_tables_detail('QA-test'))

출력

{'TableList': [
{'Name': 'security', 'DatabaseName': 'QA-test', 'Owner': 'owner', 'CreateTime': datetime.datetime(2020, 9, 10, 22, 27, 24, tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2021, 3, 1, 11, 43, 49, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(2020, 9, 10, 22, 27, 24, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor': {'Columns': [{'Name': 'assettypecode', 'Type': 'string'}, {'Name': 'industrysector', 'Type': 'varchar'}, {'Name': 'securitycode', 'Type': 'char'}, {'Name': 'contractsize', 'Type': 'string'}, {'Name': 'conversionperiodenddate', 'Type': 'string'}, {'Name': 'conversionperiodstartdate', 'Type': 'string'}, {'Name': 'expirationdate', 'Type': 'string'}, {'Name': 'issuercountrycode', 'Type': 'string'}, {'Name': 'issuercountrydesc', 'Type': 'string'}, {'Name': 'originalissuedate', 'Type': 'string'}, {'Name': 'securitynamelong', 'Type': 'string'}, {'Name': 'issueshortname', 'Type': 'string'}, {'Name': 'gicssector', 'Type': 'string'}, {'Name': 'maturitydate', 'Type': 'string'}, {'Name': 'optioncode', 'Type': 'string'}, {'Name': 'optiontypename', 'Type': 'string'}, {'Name': 'paramount', 'Type': 'string'}, {'Name': 'priceindex', 'Type': 'string'}, {'Name': 'countrycoderisk', 'Type': 'string'}, {'Name': 'countrydescrisk', 'Type': 'string'}, {'Name': 'countrycode', 'Type': 'string'}], 'Location': 's3://test/security/', 'InputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat', 'OutputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat', 'Compressed': False, 'NumberOfBuckets': -1, 'SerdeInfo': {'SerializationLibrary': 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe', 'Parameters': {'serialization.format': '1'}}, 'BucketColumns': [], 'SortColumns': [], 'Parameters': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'security', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'StoredAsSubDirectories': False}, 'PartitionKeys': [], 'TableType': 'EXTERNAL_TABLE', 'Parameters': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'security', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'CreatedBy': 'arn:aws:sts::*********:assumed-role/glue-role/AWS-Crawler'}, 'VersionId': '2'},
{'Name': 'employee', 'DatabaseName': 'QA-test', 'Owner': 'owner', 'CreateTime': datetime.datetime(2020, 9, 10, 22, 27, 24, tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2021, 3, 1, 11, 43, 49, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(2020, 9, 10, 22, 27, 24, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor': {'Columns': [{'Name': 'assettypecode', 'Type': 'string'}, {'Name': 'industrysector', 'Type': 'varchar'}, {'Name': 'code', 'Type': 'char'}, {'Name': 'size', 'Type': 'string'}, {'Name': 'countrycode', 'Type': 'string'}, {'Name': 'countrydesc', 'Type': 'string'}], 'Location': 's3://test/security/', 'InputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat', 'OutputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat', 'Compressed': False, 'NumberOfBuckets': -1, 'SerdeInfo': {'SerializationLibrary': 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe', 'Parameters': {'serialization.format': '1'}}, 'BucketColumns': [], 'SortColumns': [], 'Parameters': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'security', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'StoredAsSubDirectories': False}, 'PartitionKeys': [], 'TableType': 'EXTERNAL_TABLE', 'Parameters': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'employee', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'CreatedBy': 'arn:aws:sts::*********:assumed-role/glue-role/AWS-Crawler'}, 'VersionId': '2'}, 'ResponseMetadata': {'RequestId': '431db171-*******************0', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 01 Mar 2021 06:15:30 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '3916', 'connection': 'keep-alive', 'x-amzn-requestid': '431db171-*****************0'}, 'RetryAttempts': 0}}