Skip to content

Commit

Permalink
Merge pull request #2 from gdsc-ssu/feature
Browse files Browse the repository at this point in the history
람다 인테그레이션 변경 대응
  • Loading branch information
thinkjin99 authored Nov 5, 2023
2 parents 2e647d2 + ac2a7a9 commit 3adf408
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 46 deletions.
4 changes: 2 additions & 2 deletions caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
49 changes: 32 additions & 17 deletions lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
캐싱 로직을 전부 실행해 현재 예약 현황을 반환 합니다.
Expand All @@ -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:
"""
캐싱 람다 함수를 호출 합니다.
Expand All @@ -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
43 changes: 16 additions & 27 deletions login_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 3adf408

Please sign in to comment.