티스토리 뷰

728x90

Lambda에서 S3에 저장된 파일들의 총 리스트를 가져와서 특정 조건을 만족하는 경우 파일명을 반환하는 코드이다.

보통 boto3 라이브러리를 많이 사용하는데, 저장된 파일이 1000개 이상이 넘어갈 경우 list_objects_v2와 paginator를 사용하여 구현하여야 한다.

 

파일명을 리턴할 때 버킷명 + 폴더경로 + 파일명을 전체적으로 반환하기 때문에

replace로 앞 경로는 강제로 제거하였다.

 

import json  
import boto3
import datetime


def lambda_handler(event, context):
    # TODO implement
    
    currentTime = datetime.datetime.now()
    befcurrentTime = datetime.datetime.now() - datetime.timedelta(1)
    dirName = str(currentTime.strftime('%Y%m%d'))
    befdirName = str(befcurrentTime.strftime('%Y%m%d'))
    
    client = boto3.client('s3')
    
    #list_objects_v2
    paginator = client.get_paginator('list_objects_v2')
    
    #paginator
    response_iterator = paginator.paginate(
        Bucket='버킷명',
        Prefix='버킷의 하위 폴더 구조'
    )
    
    for page in response_iterator:
        for content in page['Contents']:
            print(content['Key'])
            print(content['LastModified'])
            chk_file_name = content['Key']
            chk_last_modi = content['LastModified']
            chk_last_modi = str(chk_last_modi.strftime('%Y%m%d'))
            
            if chk_last_modi == dirName :
                chk_file_name = chk_file_name.replace("ddd/","")
                break
            elif chk_last_modi == befdirName :    
                chk_file_name = chk_file_name.replace("ddd/","")
                break
            else :
                chk_file_name = ""
    
    print('final_file_name', chk_file_name)
                
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
글 보관함