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.

32 lines
1011 B

7 years ago
7 years ago
7 years ago
  1. from urllib.parse import urlencode
  2. from requests import get
  3. import json
  4. import os.path as osp
  5. with open(osp.join(osp.dirname(__file__),'cta_api_key')) as file:
  6. api = file.read()
  7. def get_data(type,api_key = api,**args):
  8. base_url = "http://www.ctabustracker.com/bustime/api/v2/{type}?{query}"
  9. args['key'] = api_key
  10. args['format'] = 'json'
  11. url = base_url.format(type = type,query = urlencode(args))
  12. response = get(url)
  13. data = json.loads(response.text)['bustime-response']
  14. try:
  15. data['error']
  16. raise Exception(str(data["error"]))
  17. except KeyError:
  18. return data
  19. def get_times(stop_id,api_key = api):
  20. return get_data('getpredictions',api_key,stpid=stop_id)
  21. def get_routes(api_key = api):
  22. return get_data('getroutes',api_key)
  23. def get_directions(route,api_key = api):
  24. return get_data('getdirections',api_key,rt=route)
  25. def get_stops(route,direction,api_key = api):
  26. return get_data('getstops',api_key,rt = route,dir=direction)