문제 설명 − Python에서 boto3 라이브러리를 사용하여 기존 파일 덮어쓰기를 true로 하여 주어진 로컬 경로/기본 경로에 있는 S3에서 객체를 다운로드합니다. 예를 들어 S3의 Bucket_1/testfolder에서 test.zip을 다운로드합니다.
이 문제를 해결하기 위한 접근 방식/알고리즘
1단계 − boto3 및 botocore 예외를 가져와 예외를 처리합니다.
2단계 − pathlib에서 , 파일 이름을 확인하기 위한 가져오기 경로
3단계 - s3_path, localpath 및 overwrite_existing_file download_object_from_s3 함수의 세 가지 매개변수입니다.
4단계 − s3_path 확인 s3://bucket_name/key로 AWS 형식으로 전달됩니다. . 기본적으로 localpath =없음 및 overwrite_existing_file =True . 사용자는 이 값을 전달하여 주어진 로컬 경로에서 다운로드할 수도 있습니다.
5단계 − boto3 라이브러리를 사용하여 AWS 세션을 생성합니다.
6단계 − S3용 AWS 리소스를 생성합니다.
7단계 − S3 경로를 분할하여 루트 버킷 이름과 다운로드할 객체 경로를 구분하는 작업을 수행합니다.
8단계 − overwrite_existing_file 여부 확인 False로 설정하고 파일이 이미 주어진 로컬 경로에 존재합니다. 이 경우 아무 작업도 수행하지 마십시오.
9단계 − 그렇지 않은 경우(이 조건 중 하나라도 참이 아닌 경우) 개체를 다운로드합니다. localpath가 주어지면 거기에서 다운로드하십시오. 그렇지 않으면 기본 경로로 다운로드합니다.
10단계 − 응답 코드에 따라 예외를 처리하여 파일 다운로드 여부를 확인합니다.
11단계 − 파일을 다운로드하는 동안 문제가 발생한 경우 일반 예외를 처리합니다.
예시
다음 코드를 사용하여 AWS S3에서 파일을 다운로드하십시오 -
import boto3
from botocore.exceptions import ClientError
from pathlib import Path
def download_object_from_s3(s3path, localPath=None,
overwrite_existing_file=True):
if 's3://' not in s3path:
print('Given path is not a valid s3 path.')
raise Exception('Given path is not a valid s3 path.')
session = boto3.session.Session()
s3_resource = session.resource('s3')
s3_tokens = s3path.split('/')
bucket_name = s3_tokens[2]
object_path = ""
filename = s3_tokens[len(s3_tokens) - 1]
print('Filename: ' + filename)
if len(s3_tokens) > 4:
for tokn in range(3, len(s3_tokens) - 1):
object_path += s3_tokens[tokn] + "/"
object_path += filename
else:
object_path += filename
print('object: ' + object_path)
try:
if not overwrite_existing_file and Path.is_file(filename):
pass
else:
if localPath is None:
s3_resource.meta.client.download_file(bucket_name, object_path, filename)
else:
s3_resource.meta.client.download_file(bucket_name, object_path, localPath + '/' + filename)
print('Filename: ' + filename)
return filename
except ClientError as error:
if error.response['Error']['Code'] == '404':
print(s3path + " File not found: ")
raise Exception(s3path + " File not found: ")
except Exception as error:
print("Unexpected error in download_object function of s3 helper: " + error.__str__())
raise Exception("Unexpected error in download_object function of s3 helper: " + error.__str__())
#Download into default localpath
print(download_object_from_s3("s3://Bucket_1/testfolder/test.zip"))
#Download into given path
print(download_object_from_s3("s3://Bucket_1/testfolder/test.zip","C://AWS"))
#File doesn’t exist in S3
print(download_object_from_s3("s3://Bucket_1/testfolder/abc.zip")) 출력
#Download into default localpath Filename: test.zip object: testfolder/test.zip Filename: test.zip #Download into given path Filename: test.zip object: testfolder/test.zip Filename: test.zip #File doesn’t exist in S3 Filename: abc.zip object: testfolder/abc.zip s3://Bucket_1/testfolder/abc.zip File not found: botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found
참고: 다운로드할 기본 경로는 이 함수가 작성된 디렉토리입니다. 같은 디렉토리에 로컬 경로를 제공하지 않으면 파일이 다운로드됩니다.
예를 들어 이 함수가 S3_class에 작성되고 이 클래스가 C://AWS/src/S3_class에 있는 경우 test.zip 파일이 C://AWS/src/test.zip에 다운로드됩니다.