Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng Boto3 lấy định nghĩa bảng từ AWS Glue Data Catalog

Đề bài − Sử dụng thư viện boto3 trong Python để truy xuất định nghĩa bảng của một 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 'security'.

Cách tiếp cận/Thuật toán giải quyết

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

Bước 2 − database_name và table_name là tham số bắt buộc. Nó lấy đị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 region_name được đề cập trong profile mặc định. Nếu không, hãy truyền rõ ràng region_name khi tạo phiên.

Bước 4 − Tạo client AWS cho glue.

Bước 5 − Sử dụng hàm get_table và truyền database_name làm DatabaseName và table_name làm Name.

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

Bước 7 − Xử lý ngoại lệ chung nếu có lỗi xảy ra khi kiểm tra job.

Ví dụ

Sử dụng code 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'))

Kết quả

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