# kappa123/server/runs.py import os import requests import simplejson as json import arrow import logging CACHE_AGE_MAX = 600 CACHE_LOCATION='/tmp/runs.json' logger = logging.getLogger(__name__) class GDQException(Exception): pass def inject_run_class(runs, selected_runs): output = list() for run in runs: # munge run output.append(run) return output def fetch_or_cache_runs(): if os.path.isfile(CACHE_LOCATION): ctime = os.stat(CACHE_LOCATION).st_ctime arw = arrow.get(ctime) age = (arrow.now() - arw).seconds if age > CACHE_AGE_MAX: return fetch_runs() else: return transform_runs(load_run_cache()) else: return fetch_runs() def load_run_cache(): with open(CACHE_LOCATION, 'r') as f: string = f.read() return json.loads(string) def fetch_runs(): try: logger.warn("Re-fetching cache") r = requests.get('https://gamesdonequick.com/tracker/search/?type=run&event=20', timeout=3) if r.status_code != 200: raise GDQException("GDQ not returning 200") output = r.json() with open(CACHE_LOCATION, 'w') as f: f.write(r.text) return transform_runs(output) except (GDQException, requests.exceptions.ReadTimeout): return transform_runs(load_run_cache()) def transform_runs(raw_data): """Transform a JSON list of GDQ runs from their site in to simplified dict for rendering here.""" output = list() for run in raw_data: run = run['fields'] d = { 'time': arrow.get(run['starttime']).to('America/Chicago').format('MMM DD HH:mm:ss'), 'estimate': run['run_time'], 'name': run['name'], 'category': run['category'], 'runners': run['deprecated_runners'], #lol 'order': run['order'] } output.append(d) return output