Skip to content

Commit

Permalink
feat: connect data to s3 bucket
Browse files Browse the repository at this point in the history
  • Loading branch information
Cycrypto committed Jun 3, 2024
1 parent 45953e4 commit 8136937
Show file tree
Hide file tree
Showing 11 changed files with 149 additions and 101 deletions.
2 changes: 1 addition & 1 deletion events/meal/meal_event.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@
"httpMethod": "POST",
"path": "/prod/meal/view"
},
"body": "{\"intent\":{\"id\":\"viqkzodj54puyo8ai5e6m49w\",\"name\":\"블록 이름\"},\"userRequest\":{\"timezone\":\"Asia/Seoul\",\"params\":{\"ignoreMe\":\"true\"},\"block\":{\"id\":\"viqkzodj54puyo8ai5e6m49w\",\"name\":\"블록 이름\"},\"utterance\":\"발화 내용\",\"lang\":null,\"user\":{\"id\":\"702912\",\"type\":\"accountId\",\"properties\":{}}},\"bot\":{\"id\":\"5e0f180affa74800014bd33d\",\"name\":\"봇 이름\"},\"action\":{\"name\":\"u0o68ejcea\",\"clientExtra\":null,\"params\":{\"meal\":\"view\"},\"id\":\"lwnhtra9gidojk68b6xr41o4\",\"detailParams\":{\"meal\":{\"origin\":\"view\",\"value\":\"view\",\"groupName\":\"\"}}}}",
"body": "{'bot': {'id': '5e0f180affa74800014bd33d!', 'name': '산돌이'}, 'intent': {'id': '660dfdbc8690b74ed8013553', 'name': '학식 보기_', 'extra': {'reason': {'code': 1, 'message': 'OK'}}}, 'action': {'id': '660df94d9393ef1662327b74', 'name': '학식 보기_ㅌ', 'params': {'CollegeCaF': '학식', 'TestNTT': '테스트'}, 'detailParams': {'CollegeCaF': {'groupName': '', 'origin': '학식', 'value': '학식'}, 'TestNTT': {'groupName': '', 'origin': '테스트', 'value': '테스트'}}, 'clientExtra': {}}, 'userRequest': {'block': {'id': '660dfdbc8690b74ed8013553', 'name': '학식 보기_'}, 'user': {'id': '00752cd364a4d1c910df203fd4ed424e07e6981d3f958f953c6c5ef3b879032743', 'type': 'botUserKey', 'properties': {'botUserKey': '00752cd364a4d1c910df203fd4ed424e07e6981d3f958f953c6c5ef3b879032743', 'bot_user_key': '00752cd364a4d1c910df203fd4ed424e07e6981d3f958f953c6c5ef3b879032743'}}, 'utterance': '테스트 학식', 'params': {'ignoreMe': 'true', 'surface': 'BuilderBotTest'}, 'lang': 'ko', 'timezone': 'Asia/Seoul'}, 'contexts': []}",
"isBase64Encoded": false
}
2 changes: 1 addition & 1 deletion packaged.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Resources:
Properties:
Handler: app.handler
Runtime: python3.11
CodeUri: s3://sandol-deploy-bucket/773a22c99daca4bf37a9bcfe7c23d54f
CodeUri: s3://sandol-deploy-bucket/60847926f3d6e4910d3d5df22f072833
MemorySize: 128
Timeout: 300
Policies:
Expand Down
34 changes: 14 additions & 20 deletions sandol/api_server/meal.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""

from datetime import datetime, timedelta
from typing import List

from fastapi import Request
from fastapi import APIRouter
Expand Down Expand Up @@ -215,19 +216,21 @@ async def meal_view(request: Request):
cafeteria_list: list[Restaurant] = get_meals()

# cafeteria 값이 있을 경우 해당 식당 정보로 필터링

target_cafeteria = False

cafeteria_list: List[Restaurant] = await get_meals()

if target_cafeteria:
restaurants = list(
filter(lambda x: x.name == target_cafeteria, cafeteria_list))
restaurants = list(filter(lambda x: x.name == target_cafeteria, cafeteria_list))
else:
restaurants = cafeteria_list

# 어제 7시를 기준으로 식당 정보를 필터링
standard_time = datetime.now() - timedelta(days=1)
standard_time = standard_time.replace(
hour=19, minute=0, second=0, microsecond=0)
standard_time = standard_time.replace(hour=19, minute=0, second=0, microsecond=0)

af_standard: list[Restaurant] = []
bf_standard: list[Restaurant] = []
af_standard: List[Restaurant] = []
bf_standard: List[Restaurant] = []
for r in restaurants:
if r.registration_time < standard_time:
bf_standard.append(r)
Expand All @@ -237,39 +240,30 @@ async def meal_view(request: Request):
bf_standard.sort(key=lambda x: x.registration_time)
af_standard.sort(key=lambda x: x.registration_time)

# 어제 7시 이후 등록된 식당 정보를 먼저 배치
restaurants = af_standard + bf_standard

# 점심과 저녁 메뉴를 담은 Carousel 생성
lunch_carousel, dinner_carousel = make_meal_cards(restaurants)

response = KakaoResponse()

# 점심과 저녁 메뉴 Carousel을 SkillList에 추가
# 비어있는 Carousel을 추가하지 않음
if not lunch_carousel.is_empty:
if lunch_carousel:
response.add_component(lunch_carousel)
if not dinner_carousel.is_empty:
if dinner_carousel:
response.add_component(dinner_carousel)
if response.is_empty:
response.add_component(
SimpleTextComponent("식단 정보가 없습니다.")
)
response.add_component(SimpleTextComponent("식단 정보가 없습니다."))

# 퀵리플라이 추가
# 현재 선택된 식단을 제외한 다른 식당을 퀵리플라이로 추가
if target_cafeteria:
response.add_quick_reply(
label="모두 보기",
action="message",
message_text="테스트 학식", # TODO(Seokyoung_Hong): 배포 시 '테스트' 제거
message_text="테스트 학식",
)
for rest in cafeteria_list:
if rest.name != target_cafeteria:
response.add_quick_reply(
label=rest.name,
action="message",
# TODO(Seokyoung_Hong): 배포 시 '테스트' 제거
message_text=f"테스트 학식 {rest.name}",
)

Expand Down
26 changes: 11 additions & 15 deletions sandol/api_server/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,8 @@ def check_tip_and_e(func):
"""
@wraps(func)
async def wrapper(*args, **kwargs):
# 파일의 수정 시간 확인
file_path = os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"crawler",
"data.xlsx"
)
# Lambda 환경에서 /tmp 디렉토리를 사용
file_path = "/tmp/data.xlsx"

must_download = False
if os.path.exists(file_path):
Expand All @@ -231,15 +227,15 @@ async def wrapper(*args, **kwargs):
hour=0, minute=0, second=0, microsecond=0)

# 파일 수정 시간이 이번 주 일요일 이후인지 확인
if must_download or not file_mod_datetime > start_of_week:
downloader = BookDownloader()
downloader.get_file(file_path) # data.xlsx에 파일 저장

ibook = BookTranslator()

# 식단 정보 test.json에 저장
ibook.submit_tip_info()
ibook.submit_e_info()
# if must_download or not file_mod_datetime > start_of_week:
# downloader = BookDownloader()
# downloader.get_file(file_path) # /tmp/data.xlsx에 파일 저장
#
# ibook = BookTranslator()
#
# # 식단 정보 test.json에 저장
# ibook.submit_tip_info()
# ibook.submit_e_info()

return await func(*args, **kwargs)
return wrapper
Empty file added sandol/bucket/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions sandol/bucket/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError

BUCKET_NAME = "sandol-bucket"
FILE_KEY = "test.json"


def get_s3_client():
return boto3.client('s3')


def download_file_from_s3(bucket_name, file_key, download_path):
s3 = get_s3_client()
try:
s3.download_file(bucket_name, file_key, download_path)
except (NoCredentialsError, PartialCredentialsError):
print("AWS 자격 증명이 필요합니다.")
raise
except s3.exceptions.NoSuchKey:
print(f"{file_key} 파일을 찾을 수 없습니다.")
raise FileNotFoundError(f"{file_key} 파일을 찾을 수 없습니다.")


def upload_file_to_s3(file_path, bucket_name, file_key):
s3 = get_s3_client()
try:
s3.upload_file(file_path, bucket_name, file_key)
except (NoCredentialsError, PartialCredentialsError):
print("AWS 자격 증명이 필요합니다.")
raise
12 changes: 12 additions & 0 deletions sandol/bucket/meal_bucket.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# get_meals.py

import os
import json
from common import BUCKET_NAME, FILE_KEY, download_file_from_s3


class Restaurant:
@staticmethod
def by_dict(data):
# 데이터 처리 로직 (예시)
return data
26 changes: 14 additions & 12 deletions sandol/crawler/cafeteria.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import json
import datetime as dt

from bucket.common import download_file_from_s3, BUCKET_NAME, FILE_KEY
from . import settings


Expand Down Expand Up @@ -219,20 +221,20 @@ def submit(self):

restaurant_found = False
for restaurant_data in data:
if restaurant_data["name"] == self.name: # 식당 검색
restaurant_data["lunch_menu"] = self.submit_update_menu("lunch") # 점심 메뉴 변경 사항 존재 시 submit
if restaurant_data["name"] == self.name: # 식당 검색
restaurant_data["lunch_menu"] = self.submit_update_menu("lunch") # 점심 메뉴 변경 사항 존재 시 submit
restaurant_data["dinner_menu"] = self.submit_update_menu("dinner") # 저녁 메뉴 변경 사항 존재 시 submit
restaurant_data["registration_time"] = dt.datetime.now().isoformat() # registration time update
restaurant_data["opening_time"] = self.opening_time # opining time update
restaurant_data["price_per_person"] = self.price_per_person # 가격 update
restaurant_data["registration_time"] = dt.datetime.now().isoformat() # registration time update
restaurant_data["opening_time"] = self.opening_time # opining time update
restaurant_data["price_per_person"] = self.price_per_person # 가격 update
restaurant_found = True
break

if not restaurant_found:
raise ValueError(f"레스토랑 '{self.name}'가 test.json 파일에 존재하지 않습니다.")

with open(filename, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4) # json data 한꺼번에 test.json으로 덮어씌우기
json.dump(data, file, ensure_ascii=False, indent=4) # json data 한꺼번에 test.json으로 덮어씌우기

# 임시 파일 삭제
temp_menu_path = os.path.join(current_dir, f'{self.name}_temp_menu.json')
Expand All @@ -251,23 +253,23 @@ def __str__(self):
f"Opening_time: {self.opening_time}, Price: {self.price_per_person}")


def get_meals() -> list:
current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, 'test.json')
async def get_meals() -> list:
download_path = '/tmp/test.json' # 임시 경로에 파일 다운로드

download_file_from_s3(BUCKET_NAME, FILE_KEY, download_path)

with open(filename, 'r', encoding='utf-8') as file:
with open(download_path, 'r', encoding='utf-8') as file:
data = json.load(file)

# 식당 목록 리스트
restaurants = [Restaurant.by_dict(item) for item in data]

return restaurants


if __name__ == "__main__":
# rests = get_meals()
# print(rests)
identification = "001" # 001: TIP 가가식당
identification = "001" # 001: TIP 가가식당
rest = Restaurant.by_id(identification)

print(rest)
Loading

0 comments on commit 8136937

Please sign in to comment.