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

Cách dùng Boto3 kiểm tra Glue Job có tồn tại hay không

Đề bài − Sử dụng thư viện boto3 trong Python để kiểm tra glue job có tồn tại hay không. Ví dụ: kiểm tra run_s3_file_job có tồn tại trong AWS Glue hay không.

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ố trong hàm.

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 get_job và truyền JobName.

Bước 6 − Nếu job tồn tại, response sẽ chứa tất cả chi tiết về job, ngược lại nó ném ngoại lệ.

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 để kiểm tra glue job có tồn tại hay không:

import boto3
from botocore.exceptions import ClientError

def check_glue_job_exists(job_name):
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        response = glue_client.get_job(JobName=job_name)
        return response
    except ClientError as e:
        raise Exception("boto3 client error in check_glue_job_exists: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in check_glue_job_exists: " + e.__str__())

# Kiểm tra job tồn tại
print(check_glue_job_exists("run_s3_file_job"))
# Job không tồn tại
print(check_glue_job_exists("run_s3_file_job_not_exist"))

Kết quả

# Kiểm tra job tồn tại
{'Job': {'Name': 'run_s3_file_job', 'Description': 'Glue job for the test', 'Role': 'arn:aws:iam::12345:role/delegated/glue-service-role', 'CreatedOn': datetime.datetime(2021, 02, 10, 15, 7, 3, 638000, tzinfo=tzlocal()), 'LastModifiedOn': datetime.datetime(2021, 02, 10, 15, 7, 3, 638000, tzinfo=tzlocal()), 'ExecutionProperty': {'MaxConcurrentRuns': 1}, 'Command': {'Name': 'glueetl', 'ScriptLocation': 's3://test/pipeline.py', 'PythonVersion': '3'}, 'DefaultArguments': {'--job-language': 'python', 'Step': '0'}, 'MaxRetries': 0, 'AllocatedCapacity': 4, 'Timeout': 2880, 'MaxCapacity': 4.0, 'WorkerType': 'G.1X', 'NumberOfWorkers': 4, 'GlueVersion': '2.0'}, 'ResponseMetadata': {'RequestId': 'e3ec9e2c-e75d-4443-bfea-fef674fff7e9', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 13 Feb 2021 13:20:27 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '1501', 'connection': 'keep-alive', 'x-amznrequestid': 'e3ec9e2c-e75d-4443-bfea-fef674fff7e9'}, 'RetryAttempts': 0}}
# Job không tồn tại
botocore.errorfactory.EntityNotFoundException: An error occurred (EntityNotFoundException) when calling the GetJob operation: Job with name: run_s3_file_job_not_exist not found.