From 6c7806e5cf53a63f67d9547a78e7b0eb10952202 Mon Sep 17 00:00:00 2001 From: Raphael Roberts Date: Sat, 9 Mar 2019 17:47:31 -0600 Subject: [PATCH] added timeout --- ctabus.py | 23 +++++++++++++---------- main.py | 8 +++++++- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/ctabus.py b/ctabus.py index aee9540..4ef42ea 100644 --- a/ctabus.py +++ b/ctabus.py @@ -4,12 +4,15 @@ import json from sensitive import api -def get_data(type, api_key=api, **args): +def get_data(type, api_key=api, timeout=None, **args): base_url = "http://www.ctabustracker.com/bustime/api/v2/{type}?{query}" args['key'] = api_key args['format'] = 'json' url = base_url.format(type=type, query=urlencode(args)) - response = urlopen(url) + if timeout is not None: + response = urlopen(url,timeout = timeout) + else: + response = urlopen(url) data = json.load(response)['bustime-response'] try: data['error'] @@ -18,17 +21,17 @@ def get_data(type, api_key=api, **args): return data -def get_times(stop_id, api_key=api): - return get_data('getpredictions', api_key, stpid=stop_id) +def get_times(stop_id, api_key=api, timeout=None): + return get_data('getpredictions', api_key, stpid=stop_id, timeout=timeout) -def get_routes(api_key=api): - return get_data('getroutes', api_key) +def get_routes(api_key=api, timeout=None): + return get_data('getroutes', api_key, timeout=timeout) -def get_directions(route, api_key=api): - return get_data('getdirections', api_key, rt=route) +def get_directions(route, api_key=api, timeout=None): + return get_data('getdirections', api_key, rt=route, timeout=timeout) -def get_stops(route, direction, api_key=api): - return get_data('getstops', api_key, rt=route, dir=direction) +def get_stops(route, direction, api_key=api, timeout=None): + return get_data('getstops', api_key, rt=route, dir=direction, timeout=timeout) diff --git a/main.py b/main.py index 10f16d1..a75a0b3 100755 --- a/main.py +++ b/main.py @@ -7,6 +7,7 @@ import datetime import os import re import time +import urllib # for logging import os.path as osp import sys @@ -186,11 +187,16 @@ if __name__ == '__main__': try: show(data, args.route, True) s = time.perf_counter() - data = ctabus.get_times(stop_id) + timeout = 1 + if args.periodic > timeout: + timeout = args.periodic + data = ctabus.get_times(stop_id,timeout=timeout) e = time.perf_counter() - s if e < args.periodic: time.sleep(args.periodic-e) except KeyboardInterrupt: _done = True + except urllib.error.URLError: + print("Error fetching times") else: show(data, args.route)