Skip to content

Commit

Permalink
Add read cache from s3
Browse files Browse the repository at this point in the history
s3로 부터 저장된 캐시 데이터를 읽는 api를 구현했습니다.
  • Loading branch information
thinkjin99 committed Aug 24, 2023
1 parent 084a074 commit 2224422
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
23 changes: 23 additions & 0 deletions s3/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
FROM public.ecr.aws/lambda/python:3.10

# Copy requirements.txt
COPY requirements.txt ${LAMBDA_TASK_ROOT}

#Set aws credentials
ARG AWS_REGION_NAME
ENV AWS_REGION_NAME=$AWS_REGION_NAME

ARG AWS_ACCESS_KEY_ID
ENV AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID

ARG AWS_SECRET_ACCESS_KEY
ENV AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY

#Copy code
COPY *.py ${LAMBDA_TASK_ROOT}

# Install the specified packages
RUN pip install -r requirements.txt

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "lambda_function.handler"]
42 changes: 42 additions & 0 deletions s3/lambda_function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from datetime import datetime
import json

import boto3
import pytz


def read_json_from_s3(bucket_name: str, file_key: str):
s3 = boto3.client("s3")
response = s3.get_object(Bucket=bucket_name, Key=file_key)

object_data = json.loads(response["Body"].read()) # json 파일 정보
meta_data = response["LastModified"] # 최종 캐싱 시간

last_cached_time = meta_data.astimezone(pytz.timezone("Asia/Seoul")) # UTC -> Seoul
last_cached_time = datetime.strftime(
last_cached_time, "%Y-%m-%d %H:%M:%S"
) # datetime -> str
return last_cached_time, object_data


def handler(event=None, context=None):
response = None
bucket_name = "ssudobi-cache"
file_key = "cache"
try:
last_cached_time, data = read_json_from_s3(bucket_name, file_key)
response = {
"StatusCode": 200,
"last_cached_time": last_cached_time,
"data": data,
}

except Exception as e:
response = {"StatusCode": 500, "error": str(e)}

finally:
return response


# print(read_json_from_s3("ssudobi-cache", "cache"))
# print(handler())
3 changes: 3 additions & 0 deletions s3/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
boto3==1.28.30
botocore==1.31.30
pytz==2023.3

0 comments on commit 2224422

Please sign in to comment.