Python으로 AWS S3 업로드하기
🐑 Boto3 ?
API문서
Python의 AWS SDK.
Python으로 S3, DynamoDB 등에 뚝딱하면 접근할 수 있다. 꽤 많은 이미지를 S3에 업로드와 동시에 DynamoDB에 S3 Url을 기록하기 위해 간단한 코드를 만들었다.
import
import datetime
import boto3
from boto3.s3.transfer import S3Transfer
from os import rename, listdir
이미지 이름을 좀 고유하게 만들려고 datetime을 사용했다. 지나간 시간은 되돌아오지 않아
S3 연동
client = boto3.client('s3', aws_access_key_id='**************',
aws_secret_access_key='****************')
transfer = S3Transfer(client)
DB 연동
db = boto3.resource('dynamodb',region_name='ap-northeast-2')
table = db.Table('myTableName')
access, secret key, region은 자기꺼 써주면 되고 boto3에서 key, region이 설정돼서 4line이면 이미 S3, DB 연동 끝
이름을 고유하게
today = datetime.datetime.now()
timeForUniqueImageName = str(today.year)+":"+str(today.month)+":"+str(today.day)+":"+str(today.hour)+":"+str(today.minute)+":"+str(today.second)
S3에서는 이미지 이름이 같으면 덮어버리므로 시간을 사용해 고유하게 만들어주자. 그냥 첫 라인의 today만 써줘도 되는데 난 나중에 이미지 이름을 파싱할 일이 있을 것 같아 편하게 콜론으로 구분시켜줌.
이미지 업로드
photo 디렉토리 안에 여친123 디렉토리들이 있다.
dirList = ['여친1','여친2','여친3']
for dir in dirList:
dirPath = './photo/'+dir+'/'
files = listdir(dirPath)
for name in files:
##########유니크 이미지 이름 만들기
nameAtS3 = timeForUniqueImageName+'-'+name
##########S3에 넣기
transfer.upload_file(dirPath+name, 'yourBucket.com', dir+"/"+nameAtS3,extra_args={'ACL': 'public-read'})
##########DB에 넣기
table.put_item(
Item={
'id': ttt + "-" + name,
'owner': 'moonseoklee',
'url':"https://s3.ap-northeast-2.amazonaws.com/yourBucket.com/"+dir+"/" +nameAtS3,
}
)
이런 식으로하면 로컬의 photo 디렉토리 내부의 디렉토리 구조대로 S3 버킷에 사진들이 올라가고(버킷 내부에 하위 디렉토리도 생성됨) DB에는 S3 url이 저장돼서 DB에서 url 뽑아서 S3 접근하는 식으로도 쓸 수 있다.
👉 table.put_item 부분의 id, owner는 당연히 없어도 되고 대신 id가 없으면 url이 id가 돼야겠지
👉 네이버 클라우드 보다 나만 보고싶은 사진 보관하기에 S3의 UX적 보안성은 최고인데 당연히 난 그런 사진 없음