Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Boto3 및 AWS Client를 사용하여 루트 버킷이 S3에 존재하는지 확인하는 방법은 무엇입니까?

<시간/>

문제 설명 − Python에서 Boto3 라이브러리를 사용하여 S3에 루트 버킷이 있는지 여부를 확인합니다.

− Bucket_1이 S3에 존재하거나 존재하지 않습니다.

이 문제를 해결하기 위한 접근 방식/알고리즘

1단계 − boto3 및 botocore 예외를 가져와 예외를 처리합니다.

2단계 − boto3 라이브러리를 사용하여 AWS 세션을 생성합니다.

3단계 − S3용 AWS 클라이언트를 생성합니다.

4단계head_bucket() 함수 사용 . 200 OK를 반환합니다. 버킷이 존재하고 사용자에게 액세스 권한이 있는 경우. 그렇지 않으면 응답은 403 Forbidden이 됩니다. 또는 404 찾을 수 없음 .

5단계 − 응답 코드에 따라 예외를 처리합니다.

6단계 − 버킷의 존재 여부에 따라 True/False를 반환합니다.

예시

다음 코드는 루트 버킷이 S3에 존재하는지 확인합니다 -

import boto3
from botocore.exceptions import ClientError

# To check whether root bucket exists or not
def bucket_exists(bucket_name):
   try:
      session = boto3.session.Session()
      # User can pass customized access key, secret_key and token as well
      s3_client = session.client('s3')
      s3_client.head_bucket(Bucket=bucket_name)
      print("Bucket exists.", bucket_name)
      exists = True
   except ClientError as error:
      error_code = int(error.response['Error']['Code'])
      if error_code == 403:
         print("Private Bucket. Forbidden Access! ", bucket_name)
      elif error_code == 404:
         print("Bucket Does Not Exist!", bucket_name)
      exists = False
   return exists

print(bucket_exists('bucket_1'))
print(bucket_exists('AWS_bucket_1'))

출력

Bucket exists. bucket_1
True
Bucket Does Not Exist! AWS_bucket_1
False