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

Cách dùng Boto3 chạy Glue Job trong Python

Đề bài − Sử dụng thư viện boto3 trong Python để chạy một glue job. Ví dụ: chạy job run_s3_file_job.

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 − job_name là tham số bắt buộc, arguments là tham số tùy chọn. Một số job cần arguments để chạy. Truyền arguments dưới dạng dict.

Ví dụ: arguments = {'arguments1': 'value1', 'arguments2': 'value2'}

Nếu job không cần argument, chỉ cần truyền job_name.

Bước 3 − Tạo phiên AWS bằng boto3. Đảm bảo region_name trong profile mặc định. Nếu không, 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 start_job_run và truyền JobName và arguments nếu cần.

Bước 6 − Khi job bắt đầu, nó cung cấp job_run_id kèm metadata của job.

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 để chạy glue job hiện có:

import boto3
from botocore.exceptions import ClientError

def run_glue_job(job_name, arguments={}):
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        job_run_id = glue_client.start_job_run(JobName=job_name, Arguments=arguments)
        return job_run_id
    except ClientError as e:
        raise Exception("boto3 client error in run_glue_job: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in run_glue_job: " + e.__str__())

print(run_glue_job("run_s3_file_job"))

Kết quả

{'JobRunId': 'jr_5f8136286322ce5b7d0387e28df6742abc6f5e6892751431692ffd717f45fc00', 'ResponseMetadata': {'RequestId': '36c48542-a060-468b-83cc-b067a540bc3c', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 13 Feb 2021 13:36:50 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '82', 'connection': 'keep-alive', 'x-amzn-requestid': '36c48542-a060-468b-83cc-b067a540bc3c'}, 'RetryAttempts': 0}}