Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Boto3 Waiter 기능으로 S3 버킷에 특정 키(객체)가 존재하지 않는지 확인하는 방법

문제 개요

Python의 boto3 라이브러리에서 제공하는 Waiter(대기자) 기능을 활용하여, S3 버킷 안에 특정 키(객체)가 존재하지 않는지 확인하는 방법을 알아보겠습니다. 예를 들어, Bucket_1 버킷에 test1.zip이라는 키가 없는지 Waiter를 통해 검증할 수 있습니다.

해결 접근 방식 및 알고리즘

1단계 – boto3와 botocore의 예외 처리 모듈을 임포트합니다.

2단계 – 함수의 매개변수로 bucket_name(버킷 이름)과 key(키 이름)를 받습니다.

3단계 – boto3 라이브러리를 사용해 AWS 세션을 생성합니다.

4단계 – S3를 위한 AWS 클라이언트 객체를 생성합니다.

5단계 – get_waiter 함수를 호출하여 object_not_exists 용도의 Waiter 객체를 만듭니다.

6단계 – Waiter 객체를 사용해 해당 키가 지정된 버킷에 존재하지 않는지 검증합니다. 기본적으로 성공 상태에 도달할 때까지 5초 간격으로 반복 확인하며, 20회 실패 시 오류를 반환합니다. 필요하다면 폴링 주기(Delay)와 최대 시도 횟수(MaxAttempts)를 직접 설정할 수도 있습니다.

7단계 – 대기가 정상적으로 완료되면 None을 반환합니다.

8단계 – 버킷 확인 과정에서 문제가 발생한 경우 일반 예외(generic exception)를 처리합니다.

예제 코드

아래 코드를 사용하면 Waiter를 통해 버킷 내 키의 부재 여부를 확인할 수 있습니다.

import boto3
from botocore.exceptions import ClientError

def use_waiters_check_object_not_exists(bucket_name, key_name):
    session = boto3.session.Session()
    s3_client = session.client('s3')
    try:
        waiter = s3_client.get_waiter('object_not_exists')
        waiter.wait(Bucket=bucket_name, Key=key_name,
                    WaiterConfig={
                        'Delay': 2, 'MaxAttempts': 5})
        print('Object does not exist: ' + bucket_name + '/' + key_name)
    except ClientError as e:
        raise Exception("boto3 client error in use_waiters_check_object_not_exists: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in use_waiters_check_object_not_exists: " + e.__str__())

print(use_waiters_check_object_exists("Bucket_1", "testfolder/test1.zip"))
print(use_waiters_check_object_exists("Bucket_1", "testfolder/test.zip"))

실행 결과

Object does not exist: Bucket_1/testfolder/test1.zip
None

botocore.exceptions.WaiterError: Waiter ObjectNotExists failed: Max attempts exceeded
"Unexpected error in use_waiters_check_object_not_exists: " + e.__str__())
Exception: Unexpected error in use_waiters_check_object_not_exists:
Waiter ObjectNotExists failed: Max attempts exceed

결과 해석

Bucket_1/testfolder/test1.zip의 경우, 해당 객체가 실제로 존재하지 않기 때문에 print 문이 실행되고, 함수 자체는 아무 값도 반환하지 않으므로 None이 함께 출력됩니다.

반면 Bucket_1/testfolder/test.zip의 경우 이 객체가 실제로 존재하기 때문에, 최대 시도 횟수(MaxAttempts)를 초과하게 되며 예외가 발생합니다.

예외 메시지에서 "Max attempts exceeded"라는 문구를 통해, 설정한 재시도 횟수 내에 객체가 삭제되지 않았음을(즉, 객체가 계속 존재함을) 확인할 수 있습니다.