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 phiên bản cụ thể 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' cho phiên bản 2.

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, table_name và version_id là tham số bắt buộc. Nó lấy định nghĩa của bảng cho phiên bản được chỉ định.

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_version và truyền database_name làm DatabaseName, table_name làm TableName và version_id làm VersionId. Lưu ý version_id là chuỗi nên giá trị số nguyên phải truyền trong dấu nháy đơn.

Bước 6 − Nó trả về định nghĩa của bảng cho phiên bản được chỉ định.

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 cho phiên bản cụ thể:

import boto3
from botocore.exceptions import ClientError

def retrieves_table_version_details(database_name, table_name, version_id):
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        response = glue_client.get_table_version(
            DatabaseName=database_name,
            TableName=table_name,
            VersionId=version_id
        )
        return response
    except ClientError as e:
        raise Exception("boto3 client error in retrieves_table_version_details: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in retrieves_table_version_details: " + e.__str__())

print(retrieves_table_version_details('QA-test', 'security', '2'))

Kết quả

{'TableVersion': {'Table': {'Name': 'security', 'DatabaseName': 'QAtest', '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'}, 'ResponseMetadata': {'RequestId': '431db171- *******************0', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 01 Mar 2021 06:15:30 GMT', 'content-type': 'application/x-amzjson-1.1', 'content-length': '3916', 'connection': 'keep-alive', 'xamzn-requestid': '431db171-*****************0'}, 'RetryAttempts': 0}}