diff --git a/caching.py b/caching.py index f0e5574..5f7eb93 100644 --- a/caching.py +++ b/caching.py @@ -82,7 +82,7 @@ async def get_reservation_status( return reservation_status except asyncio.CancelledError: - print(f">> Canceled date:{date} room_number:{room_number}") + print(f">> Canceled date:{date} room_number:{room_number}") # 실행중 에러가 발생한 경우 async def get_all_rooms_reservation_status( @@ -154,7 +154,7 @@ async def get_all_days_reservation_status(retry_client: RetryClient) -> dict: async def get_cache_data(retry_client: RetryClient): - date = "2023-08-28" # 조회 날짜 + # date = "2023-08-28" # 조회 날짜 # room_number = 1 async with retry_client: # res = await get_reservation_status(retry_client, date, room_number) diff --git a/lambda_function.py b/lambda_function.py index 2777660..5ebd2f0 100644 --- a/lambda_function.py +++ b/lambda_function.py @@ -5,10 +5,10 @@ import json from caching import get_cache_data -from login_session import get_logined_session, create_retry_client +from login_session import * -async def main(token: str) -> dict: +async def update_cache(student_id: str, password: str) -> dict: """ 캐싱 로직을 전부 실행해 현재 예약 현황을 반환 합니다. @@ -19,13 +19,32 @@ async def main(token: str) -> dict: Returns: dict: """ - session = await get_logined_session(token) # 로그인 및 세션 생성 + session = await get_logined_session(student_id, password) # 로그인 세션 생성 retry_client = await create_retry_client(session) # 세션에 retry 기능 추가 cache_data = await get_cache_data(retry_client) # 예약 현황 추출 + await retry_client.close() + return cache_data -def handler(event: dict, context: dict) -> dict | None: +def put_cache_s3(cache: dict): + s3 = boto3.client("s3") + s3.put_object( + Bucket="ssudobi-cache", Key="cache", Body=json.dumps(cache) + ) # 캐시 업데이트 + + +def create_response(status_code: str | int, msg: str) -> dict: + response = { + "isBase64Encoded": False, + "headers": {"Content-Type": "application/json"}, + "statusCode": status_code, + "body": msg, + } + return response + + +def handler(event: dict, context: dict) -> dict: """ 캐싱 람다 함수를 호출 합니다. @@ -36,25 +55,21 @@ def handler(event: dict, context: dict) -> dict | None: Returns: dict: 람다 함수 실행 결과 값 """ - response = None + response = create_response(200, "empty") try: - token = event.get("token") # 로그인 토큰 조회 - if not token: - raise AssertionError("Token is not passed") # 토큰이 없는 경우 - - res = asyncio.run(main(token)) # 예약 현황 조회 - s3 = boto3.client("s3") - s3.put_object( - Bucket="ssudobi-cache", Key="cache", Body=json.dumps(res) - ) # 캐시 업데이트 - response = {"StatusCode": 200, "data": res} + body = json.loads(event["body"]) + student_id = body["student_id"] + password = body["password"] + res = asyncio.run(update_cache(student_id, password)) # 예약 현황 조회 + # put_cache_s3(res) + response = create_response(200, json.dumps({"data": res})) except AssertionError as e: - response = {"StatusCode": 422, "error": str(e)} # 엔티티 에러 + response = create_response(401, json.dumps({"data": str(e)})) except Exception as e: - response = {"StatusCode": 500, "error": str(e)} # 서버 자체 에러 + response = create_response(500, json.dumps({"data": str(e)})) finally: return response diff --git a/login_session.py b/login_session.py index 7fde0b2..1d5da91 100644 --- a/login_session.py +++ b/login_session.py @@ -22,40 +22,29 @@ async def create_retry_client(session: aiohttp.ClientSession) -> RetryClient: return retry_client -async def get_logined_session(token: str) -> aiohttp.ClientSession: - """ - 로그인이 반영된 비동기 세션을 생성 합니다. - - Returns: - ClientSession: 로그인 처리가 완료된 세션 - """ - session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3)) # 세션 생성 - try: - headers = { - "Accept": "application/json, text/plain, */*", - "pyxis-auth-token": token, - } - session.headers.update(headers) - - except KeyError as e: - raise KeyError(f">> Login failed {e}") - - return session - - -async def login(usaint_id: str, password: str) -> dict: +async def get_logined_session(usaint_id: str, password: str) -> aiohttp.ClientSession: """ 로그인을 진행하고 인증 토큰을 발급합니다. Returns: str: 인증 토큰 값 """ - login_url = "https://oasis.ssu.ac.kr/pyxis-api/api/login" # 로그인 api - data = {"loginId": usaint_id, "password": password} - async with aiohttp.ClientSession() as session: + session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3)) + try: + login_url = "https://oasis.ssu.ac.kr/pyxis-api/api/login" # 로그인 api + data = {"loginId": usaint_id, "password": password} async with session.post(login_url, json=data) as resp: json_res = await resp.json() # 토큰 추출 - return json_res + assert json_res["code"] == "success.loggedIn", "Login Failed" # 로그인 검증 + + headers = { + "Accept": "application/json, text/plain, */*", + "pyxis-auth-token": json_res["data"]["accessToken"], + } + session.headers.update(headers) + return session -# if __name__ == "__main__": + except AssertionError as e: + await session.close() + raise e