bin/time-in: refactor

This commit is contained in:
Henrik Lissner 2017-04-22 01:58:55 -04:00
parent dd6a0254c1
commit a760a43502

View file

@ -29,36 +29,29 @@ CACHE = {}
def _generate_url(url, *args): def _generate_url(url, *args):
return url.format(*map(request.quote, map(str, args))) return url.format(*map(request.quote, map(str, args)))
def get_timezone(lat, lng, timestamp): def _request(url, *args):
try: try:
url = _generate_url(URL_TZ, lat, lng, timestamp) real_url = url.format(*map(request.quote, map(str, args)))
resp = request.urlopen(url).read() resp = request.urlopen(real_url).read()
result = json.loads(resp.decode('utf-8')) result = json.loads(resp.decode('utf-8'))
if result['status'] == 'OK': if result['status'] == 'OK':
return result['timeZoneId'] return result
elif result['status'] != 'UNKNOWN_ERROR': elif result['status'] != 'UNKNOWN_ERROR':
raise Exception(result['error_message']) raise Exception(result['error_message'])
except IOError: except IOError:
print("IOError") print("IOError") # FIXME Better error handling
def get_timezone(lat, lng, timestamp):
return _request(URL_TZ, lat, lng, timestamp)['timeZoneId']
def get_coords(desc): def get_coords(desc):
try: result = _request(URL_GEOCODE, desc)
url = _generate_url(URL_GEOCODE, desc) if result['results']:
resp = request.urlopen(url).read() return {
result = json.loads(resp.decode('utf-8')) "lat": result['results'][0]['geometry']['location']['lat'],
if result['status'] == 'OK': "lng": result['results'][0]['geometry']['location']['lng'],
if result['results']: "name": result['results'][0]['formatted_address']
return { }
"lat": result['results'][0]['geometry']['location']['lat'],
"lng": result['results'][0]['geometry']['location']['lng'],
"name": result['results'][0]['formatted_address']
}
else:
return None
elif result['status'] != 'UNKNOWN_ERROR':
raise Exception(result['error_message'])
except IOError:
print("IOError")
def cache(key, fn, ttl): def cache(key, fn, ttl):
if key in CACHE and CACHE[key]['time'] < CACHE[key]['time'] + ttl: if key in CACHE and CACHE[key]['time'] < CACHE[key]['time'] + ttl: