You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.2 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. from urllib.parse import urlencode
  2. from urllib.request import urlopen
  3. from disk_cache import disk_cache
  4. import json
  5. from sensitive import api
  6. def get_data(type, api_key=api, timeout=None, **args):
  7. base_url = "http://www.ctabustracker.com/bustime/api/v2/{type}?{query}"
  8. args['key'] = api_key
  9. args['format'] = 'json'
  10. url = base_url.format(type=type, query=urlencode(args))
  11. if timeout is not None:
  12. response = urlopen(url, timeout=timeout)
  13. else:
  14. response = urlopen(url)
  15. data = json.load(response)['bustime-response']
  16. try:
  17. data['error']
  18. raise Exception(str(data["error"]))
  19. except KeyError:
  20. return data
  21. def get_times(stop_id, api_key=api, timeout=None):
  22. return get_data('getpredictions', api_key, stpid=stop_id, timeout=timeout)
  23. @disk_cache
  24. def get_routes(api_key=api, timeout=None):
  25. return get_data('getroutes', api_key, timeout=timeout)
  26. @disk_cache
  27. def get_directions(route, api_key=api, timeout=None):
  28. return get_data('getdirections', api_key, rt=route, timeout=timeout)
  29. @disk_cache
  30. def get_stops(route, direction, api_key=api, timeout=None):
  31. return get_data('getstops', api_key, rt=route, dir=direction, timeout=timeout)