Cloud Engineering/AWS
[AWS] Python boto3 로 S3 Bucket에 파일 업로드하기
minjiwoo
2023. 7. 23. 21:55
728x90
boto3 library 가 없으면 우선
pip3 install boto3 명령어로 설치해주자.
또한 AWS 콘솔에서 ACCESS_KEY 와 SECRET_ACCESS_KEY 발급이 필요하다 !!
다음으로 S3 버킷 연결을 위한 connection을 생성하는 과정이다 client() 함수로 연결을 생성한다.
import boto3
def s3_connection():
try:
s3 = boto3.client(
service_name="s3",
region_name="ap-northeast-2",
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
except Exception as e:
print(e)
else:
print("S3 bucket connected!")
return s3
S3 버킷과의 연결을 담당하는 객체 s3 를 통해, upload_file() 을 할 수 있다.
def s3_upload_object(filepath, access_key):
s3 = s3_connection()
try:
s3.upload_file(
Filename=filepath,
Bucket=S3_BUCKET,
Key=access_key,
ExtraArgs={"ContentType":"application/json"} # parquet
)
except Exception as e:
print("error:", e)
return False
return True
# s3_upload_object(S3_BUCKET, "test.parquet", "test/test.parquet")
# Filename = File path to upload -> 업로드할 파일 경로
# Bucket = Name of the bucket to upload the file
# Key = Name of the key upload to S3 -> S3에서 파일 경로
주의할 점은 여기서 Filename은 현재 내가 업로드하고 싶은 파일의 local directory 이고, Key는 S3 버킷에 올리게 될 key 값 , 즉 S3에서의 경로를 적어주면 된다.
728x90