Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để sử dụng Boto3 để lấy định nghĩa bảng của cơ sở dữ liệu từ Danh mục dữ liệu keo AWS?

Tuyên bố sự cố - Sử dụng thư viện boto3 trong Python để truy xuất định nghĩa bảng của cơ sở dữ liệu.

Ví dụ - Truy xuất định nghĩa bảng của cơ sở dữ liệu ‘QA-test’ và bảng là ‘bảo mật’.

Phương pháp tiếp cận / Thuật toán để giải quyết vấn đề này

Bước 1 - Nhập các ngoại lệ boto3 và botocore để xử lý các ngoại lệ.

Bước 2 - database_name table_name là tham số bắt buộc. Nó tìm nạp định nghĩa của bảng đã cho.

Bước 3 - Tạo phiên AWS bằng thư viện boto3. Đảm bảo rằng region_name được đề cập trong hồ sơ mặc định. Nếu nó không được đề cập, thì hãy chuyển region_name một cách rõ ràng trong khi tạo phiên.

Bước 4 - Tạo ứng dụng AWS cho keo dán.

Bước 5 - Bây giờ sử dụng hàm get_table và chuyển database_name dưới dạng DatabaseName và table_name dưới dạng tham số Tên.

Bước 6 - Nó trả về định nghĩa của một bảng nhất định. Nếu bảng có nhiều phiên bản, bảng luôn tìm nạp thông tin chi tiết từ phiên bản hiện tại / mới nhất của bảng.

Bước 7 - Xử lý ngoại lệ chung nếu có sự cố xảy ra trong khi kiểm tra công việc.

Ví dụ

Sử dụng mã sau để truy xuất định nghĩa bảng của cơ sở dữ liệu -

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'))

Đầu ra

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