MJay
코드보면서 공부해보기 본문
from datetime import datetime, timedelta, timezone
import boto3
import pymysql
# 00. AWS Resource Initialize
dynamodb = boto3.resource('dynamodb')
# 01. UTC to Local Converter
def convert_utc_to_local(utctime_str, offset):
return datetime.strptime(utctime_str, "%Y-%m-%d %H:%M:%S") \
.replace(tzinfo=timezone.utc).astimezone(tz=timezone(timedelta(hours=offset))) \
.strftime("%Y-%m-%d %H:%M:%S %Z")
offset이란
offset이란 변위차이라고 한다.
astimezone은 localtime에 맞게 바꿔주는것같다.
def lambda_handler(event, context):
# 02. MySQL and DynamoDB Instance
mysql_g2_obj = pymysql.connect(host=“mj3.*****.us-east-1.rds.amazonaws.com",
user="mj", passwd=“****", db="g2instance", connect_timeout=5)
mysql_migration_obj = pymysql.connect(host=“mj3.****.us-east-1.rds.amazonaws.com", user="mj",
passwd=“*****",
db="migration", connect_timeout=5)
dynamo_obj = dynamodb.Table('g2-instance')
# 03. Request Params
param_local = int(event.get('local', 0))
event.get의 지원하는 type는 int, str 등등 dictionary이다.
# 04. Get current pricetable
pricetable = dynamo_obj.scan()
resp_pricetable_dict = {}
for item in pricetable["Items"]:
resp_pricetable_dict[str(item['az'])] = item['price']
# 05. Get last information (Current az, current price of az, current steps, last update time)
with mysql_g2_obj.cursor() as cur:
resp_lastinfo_dict = {}
cur.execute("select * from Spottable ORDER BY Time DESC LIMIT 1")
try:
row = cur.fetchall()[0]
resp_lastinfo_dict["time"] = convert_utc_to_local(str(row[0]), param_local)
resp_lastinfo_dict["az"] = row[1]
resp_lastinfo_dict["price"] = row[2]
resp_lastinfo_dict["step"] = int(row[3])
except:
pass
mysql_g2_obj.close()
# 06. Get migration route
with mysql_migration_obj.cursor() as cur:
resp_migration_list = []
cur.execute("select az,current_price,time from Route ORDER BY id ASC")
rows = cur.fetchall()
for row in rows:
resp_migration_list.append({
"az": str(row[0]),
"price": row[1],
"time": convert_utc_to_local(str(row[2]), param_local) if row[2] else None
})
row[2]가 true이면 저 함수를 쓰고 else 면 아무것도 아니라는 건거 같다. None이라고 처리해주는 거 같다.
mysql_migration_obj.close()
# 07. Return JSON
return {
"pricetable": resp_pricetable_dict,
"lastinfo": resp_lastinfo_dict,
"migration": resp_migration_list
}
동언이 보기 좋게 잘 짠듯 낼 다시 봐봐야겠다 좋은 코드라고 느낄수있다.
'Cloud Computing' 카테고리의 다른 글
더블 버퍼링 (0) | 2017.08.29 |
---|---|
행렬에서의 BFS,DFS (0) | 2017.07.26 |
CherryPick PPT 만들었습니다. (0) | 2017.05.10 |
What is overhead? (0) | 2017.05.06 |
Celery 간단 요약 정리 2 (0) | 2017.04.09 |