Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Boto3 ดึงนิยามตาราง (Table Definition) จาก AWS Glue Data Catalog

ข้อกำหนดปัญหา: ใช้ไลบรารี Boto3 ใน Python เพื่อดึงนิยามตารางของฐานข้อมูล

ตัวอย่าง: ดึงนิยามตารางของฐานข้อมูล 'QA-test' และตาราง 'security'

ขั้นตอนการแก้ปัญหา

  1. ขั้นตอน 1: นำเข้า boto3 และ botocore exceptions เพื่อจัดการข้อผิดพลาด
  2. ขั้นตอน 2: database_name และ table_name เป็นพารามิเตอร์บังคับ ใช้ดึงนิยามของตารางที่กำหนด
  3. ขั้นตอน 3: สร้าง AWS session ด้วย Boto3 ตรวจสอบว่า region_name ถูกตั้งค่าในโปรไฟล์เริ่มต้น หากไม่ได้ ต้องระบุ region_name อย่างชัดเจน
  4. ขั้นตอน 4: สร้าง AWS client สำหรับ Glue
  5. ขั้นตอน 5: ใช้ฟังก์ชัน get_table ส่ง database_name เป็น DatabaseName และ table_name เป็น Name parameter
  6. ขั้นตอน 6: คืนค่านิยามของตารางที่กำหนด หากตารางมีหลายเวอร์ชัน จะดึงรายละเอียดจากเวอร์ชันปัจจุบัน/ล่าสุดเสมอ
  7. ขั้นตอน 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}}