S3 storage를 위한 boto3 사용법 정리

S3 storage를 위한 boto3 사용법 정리

2021, May 19    



  • 현재 S3 storage에서 파일 및 폴더를 업/다운로드 하고 싶으시면 아래 깃의 코드를 사용하기를 추천 드립니다. 제가 작성하였고 저 또한 즐겨 사용하고 있습니다. 자세한 사용 방법등은 아래 링크에서 확인할 수 있으며 문의 사항 있으면 댓글 부탁 드립니다.


S3 storage에서 폴더 다운 받기


import boto3
import os 

# set aws credentials 
s3r = boto3.resource('s3', aws_access_key_id='xxxxxxxxxxxxxxxxx',
    aws_secret_access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
bucket = s3r.Bucket('bucket_name')

# downloading folder 
prefix = 'dirname'
for object in bucket.objects.filter(Prefix = 'dirname'):
    if object.key == prefix:
        os.makedirs(os.path.dirname(object.key), exist_ok=True)
        continue;
    bucket.download_file(object.key, object.key)


S3 storage에 데이터 업로드


import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')


s3 storage에 폴더 업로드


def uploadDirectory(path,bucketname):
        for root,dirs,files in os.walk(path):
            for file in files:
                s3C.upload_file(os.path.join(root,file),bucketname,file)


S3 storage에 데이터가 있는 지 확인


  • 아래 코드를 이용하여 s3 storage에 파일 존재 유무를 확인하는 방법이 가장 간단한 방법 중 하나입니다.
  • path에 해당하는 부분에 경로 이름 또는 파일 이름을 입력하였을 경우에 일치하면 True를 반환합니다.
def prefix_exits(bucket, path):
    s3_client = boto3.client('s3')
    res = s3_client.list_objects_v2(Bucket=bucket, Prefix=path, MaxKeys=1)
    return 'Contents' in res


multipart 업/다운로드를 이용한 동시성 작업 (concurrency)


import boto3
from boto3.s3.transfer import TransferConfig

# Set the desired multipart threshold value (5GB) with 5 max concurrency
GB = 1024 ** 3
config = TransferConfig(multipart_threshold=5*GB, max_concurrency=5)

# Perform the transfer
s3 = boto3.client('s3')
s3.upload_file('FILE_NAME', 'BUCKET_NAME', 'OBJECT_NAME', Config=config)