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

AWS 리소스에 있는 S3에서 객체의 모든 버전 목록을 가져오는 방법

<시간/>

이 기사에서는 AWS 리소스에 있는 객체의 모든 버전 목록을 S3에서 가져오는 방법을 알아봅니다.

test.zip의 모든 버전 나열 Bucket_1/testfolder에서 S3.

문제 설명: boto3 사용 Python의 라이브러리를 사용하여 S3에서 객체의 모든 버전 목록을 가져옵니다.

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

  • 1단계: boto3 가져오기 및 보토코어 예외를 처리하는 예외.

  • 2단계: bucket_name은 필수 매개변수입니다.

  • 3단계: boto3 lib를 사용하여 AWS 세션 생성

  • 4단계: s3용 AWS 클라이언트 생성

  • 5단계: 이제 list_object_versions 함수를 사용하여 주어진 버킷의 모든 객체 버전을 나열합니다. 예외가 있는 경우 처리합니다.

  • 6단계: 위 함수의 결과는 사전이며 주어진 버킷에 있는 객체의 모든 버전을 포함합니다.

  • 7단계: 개체의 모든 버전 목록을 반환합니다.

예시 코드

다음 코드를 사용하여 AWS S3에서 객체의 모든 버전 목록 가져오기 -

import boto3
from botocore.exceptions import ClientError

def list_all_objects_version(bucket_name, prefix_name):  
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
      result = s3_client.list_object_versions(Bucket=bucket_name, Prefix=prefix_name)
   except ClientError as e:
      raise Exception("boto3 client error in list_all_objects_version function: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in list_all_objects_version function of s3 helper: " + e.__str__())
print(list_all_objects_version("Bucket_1","testfolder"))

출력

{'ResponseMetadata': {'RequestId': 'H4VAGM3YP6', 'HostId': ***********', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': ***************', 'x-amz-request-id': 'H4VAGM3YP6', 'date': 'Sat, 03 Apr 2021 08:04:08 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': False, 'KeyMarker': '', 'VersionIdMarker': '',
'Versions': [{'ETag': '"705e2e674b04ca71"', 'Size': 1773, 'StorageClass': 'STANDARD', 'Key': 'testfolder/test.zip', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 12, 18, 14, 13, 18, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928*******************************'}}], 'Name': 'Bucket_1', 'Prefix': 'testfolder', 'MaxKeys': 1000, 'EncodingType': 'url'}