Created
September 9, 2018 16:08
-
-
Save yasuabe/01104151f142b880c985c2c094e39320 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import re | |
import logging | |
from urllib.parse import unquote | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def lambda_handler(event, context): | |
logger.info(json.dumps(event)) | |
req = parse(event['body']) | |
return { | |
"statusCode": 200, | |
"body": switch[req['command']](req['text']) | |
} | |
def parse(body): | |
return dict(map(to_key_value, body.split('&'))) | |
def to_key_value(s): | |
return list(map(lambda pair: unquote(pair).replace('+', ' '), s.split('=', 1))) | |
switch = { | |
'/f2c': lambda text: convert_with(text, f2c_string), | |
'/c2f': lambda text: convert_with(text, c2f_string) | |
} | |
def convert_with(text, converter): | |
words = list(filter(bool, re.compile("\s+").split(text))) | |
return "\r\n".join(list(map(converter, words))) | |
f2c_string = lambda f: convert(f, fahrenheit_to_celcius) | |
c2f_string = lambda c: convert(c, celcius_to_fahrenheit) | |
def convert(w, f): | |
try: | |
return str(f(int(w))) | |
except Exception as e: | |
return "---" | |
fahrenheit_to_celcius = lambda f: (f - 32) * 5 / 9 | |
celcius_to_fahrenheit = lambda c: c * 9 / 5 + 32 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment