Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Boto3로 AWS Glue Data Catalog의 데이터베이스 테이블 정의 가져오기

문제 상황 − Python에서 boto3 라이브러리를 사용하여 특정 데이터베이스에 속한 테이블의 정의(스키마 정보)를 조회하고자 합니다.

예시 − 'QA-test'라는 데이터베이스에서 'security'라는 이름의 테이블 정의를 가져와 보겠습니다.

해결 접근 방식 및 알고리즘

1단계 − 예외 처리를 위해 boto3와 botocore.exceptions 모듈을 임포트합니다.

2단계database_nametable_name은 필수 매개변수입니다. 이 두 값을 통해 해당 테이블의 정의를 조회합니다.

3단계 − boto3 라이브러리로 AWS 세션을 생성합니다. 기본 프로필에 region_name이 설정되어 있는지 확인하세요. 만약 설정되어 있지 않다면, 세션을 생성할 때 region_name을 명시적으로 전달해야 합니다.

4단계 − Glue 서비스를 위한 AWS 클라이언트를 생성합니다.

5단계 − get_table 함수를 호출하면서 database_name을 DatabaseName에, table_name을 Name 파라미터에 각각 전달합니다.

6단계 − 함수는 지정된 테이블의 정의를 반환합니다. 테이블에 여러 버전이 존재하는 경우, 항상 현재 최신 버전의 상세 정보를 가져옵니다.

7단계 − 작업 수행 중 오류가 발생할 경우를 대비해 일반 예외도 함께 처리합니다.

예제 코드

다음 코드를 사용하여 데이터베이스 내 테이블의 정의를 조회할 수 있습니다 −

import boto3
from botocore.exceptions import ClientError

def retrieves_table_details(database_name, table_name)
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        response = glue_client.get_table(DatabaseName = database_name, Name = table_name)
        return response
    except ClientError as e:
        raise Exception("boto3 client error in retrieves_table_details: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in retrieves_table_details: " + e.__str__())
print(retrieves_table_details('QA-test', 'security'))

실행 결과

{'Table': {'Name': 'security', 'DatabaseName': 'QA-test', 'Owner':
'owner', 'CreateTime': datetime.datetime(2020, 9, 10, 22, 27, 24,
tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2021, 2, 28, 10, 37,
33, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(2020, 9, 10,
22, 27, 24, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor':
{'Columns': [{'Name': 'assettypecode', 'Type': 'string'}, {'Name':
'industrysector', 'Type': 'string'}, {'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'},
'ResponseMetadata': {'RequestId': '4c108dd5-***************76ac',
'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 01 Mar 2021
06:04:58 GMT', 'content-type': 'application/x-amz-json-1.1',
'contentlength': '3882', 'connection': 'keep-alive',
'x-amzn-requestid': '4c108dd5-*********************676ac'},
'RetryAttempts': 0}}