AWS

1-1. AWS S3 사용하기 (boto3 이용)

황수진 2021. 12. 23. 16:47

* 이 포스팅은 https://developing-soosoo.tistory.com/48 과 연결된 포스팅입니다.

* https://boto3.amazonaws.com/v1/documentation/api/latest/index.html 를 바탕으로 작성했습니다

 

Boto3 documentation — Boto3 Docs 1.20.26 documentation

You use the AWS SDK for Python (Boto3) to create, configure, and manage AWS services, such as Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). The SDK provides an object-oriented API as well as low-level access to AW

boto3.amazonaws.com

 

 

이전 포스팅인 '1-0 AWS S3 시작하기' 에서 S3 초기 셋팅 (버킷 만들기)를 완성했습니다.

예제 코드를 참고해 boto3를 기반으로 S3를 사용해보겠습니다!

 

 

1. bucket 조회하기 (list)

import boto3

# S3 client 생성하기
s3=boto3.client('s3',region_name='ap-northease-2')

# S3에서 bucket list 불러오기
response=s3.list_buckets()

# reponse 통해서 전체 bucket name 불러오기
buckets=[bucket['Name']for bucket in response['Buckets']]

# bucket list 프린트하기
print("Bucket List: %s"%buckets)

client(), list_buckets()

 

*다른 방법

import boto3

s3=boto3.resource('s3')

# 1
print(s3.buckets.all())
>> s3.bucketsCollection(s3.ServiceResource(),s3.Bucket)

# 2 각각 bucket 이름을 알고 싶을 때
for bucket in s3.buckets.all():
	print(bucket)

>>s3.Bucket(name='bucket1')
>>s3.Bucket(name='bucket2')
>>...

 

 

2. bucket 만들기 (create)

import boto3

# s3 client 생성하기
s3=boto3.client('s3')

s3.create_bucket(Bucket='bucket_name',CreateBucketConfiguration={'LocationConstraint':'op-northease-2'})

create_bucket(), Bucket='bucket_name', CreateBucketConfiguration={'LocationConstraint':''}

 

 

3. bucket에 파일 업로드하기 (upload)

import boto3

# S3 client 만들기
s3=boto3.client('s3')

filename='upload.py'
bucket_name='bucket_name'

# managed uploader를 이용해 업로드한다 
s3.upload_file(filename,bucket_name,filename) 
# 첫번째 file name : 현재 업로드할 파일의 이름
# 두번째 file name : 업로드할 때 저장할 이름

upload_file(filename,bucket_name,filename)

 

 

4. bucket에 있는 파일 다운받기 (download)

import boto3
import botocore

BUCKET_NAME='bucketname' # bucket name
KEY='upload.py' # object key

s3=boto3.resoure('s3')

try:
	s3.Bucket(BUCKET_NAME).download_file(KEY,'my_local_upload.py')
except botocore.exceptions.ClientError as e:
	if e.response['Error']['Code']=="404":
    	print("The object does not exist.")
    else:
    	raise
    # S3를 사용하고 파일을 업로드하게 되면, 각각 URL이 생성된다

(botocore는 AWS-CLI command line utility 기반으로 제공하는 서비스입니다. boto3.x project에 중요한 역할을 합니다)

자세히 알아보고 싶으시면 https://botocore.amazonaws.com/v1/documentation/api/latest/index.html 를 참고하세요!