티스토리 뷰

Technology/AWS, Docker

AWS 람다에서 S3 접근

캡틴테크 2023. 3. 13. 17:27
반응형

오늘은 AWS 람다 python을 통해서 S3에 접근하는 방법에 대해서 살펴보도록 하겠습니다. 먼저 실제 코드부터 확인하도록 하겠습니다.

import json
import boto3

BUCKET_NAME = 's3-bucket-name'
KEY = 'test.json'

s3_client = boto3.client('s3')

def lambda_handler(event, context):
    data = s3_client.get_object(Bucket=BUCKET_NAME, Key=KEY)
    content = data['Body'].read()
		refined_content = content.decode('UTF-8')
    print(content)
		print(refined_content)

    return {
        'statusCode': 200,
        'body': json.dumps(refined_content)
    }

 

알아야 할 것들

AWS 람다 함수에서 S3에 접근하기 위해서는 아래가 필요하다.

  • boto3를 통한 S3 클라이언트
    • s3_client = boto3.client('s3')
  • 파일이 저장된 버킷명, BUCKET_NAME
    • BUCKET_NAME = 's3-bucket-name'
  • 파일 이름, KEY
    • KEY = 'test.json'
  • get_object를 통한 객체 획득
    • data = s3_client.get_object(Bucket=BUCKET_NAME, Key=KEY)
  • read() 함수를 통한 데이터 읽기
    • content = data['Body'].read()
  • decode() 함수를 통한 데이터 디코딩
    • refined_content = content.decode('UTF-8')

이제 자신의 S3의 버킷 네임을 알고 있다면  쉽게 구현해볼 수 있겠죠?

반응형
댓글