From e081f8686127e2ef4dcf5034bef68132e663252c Mon Sep 17 00:00:00 2001 From: Jake Conway Date: Wed, 15 Jun 2016 17:32:09 +0000 Subject: [PATCH] Initial commit - includes CTA Bus tracker only at this time --- .gitignore | 90 ++++++++++++++++++++++ LICENSE.txt | 8 ++ README.rst | 24 ++++++ chicagotransit/cta.py | 157 +++++++++++++++++++++++++++++++++++++++ chicagotransit/errors.py | 13 ++++ requirements.txt | 2 + setup.cfg | 0 setup.py | 35 +++++++++ 8 files changed, 329 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.txt create mode 100644 README.rst create mode 100644 chicagotransit/cta.py create mode 100644 chicagotransit/errors.py create mode 100644 requirements.txt create mode 100644 setup.cfg create mode 100644 setup.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5e0fa61 --- /dev/null +++ b/.gitignore @@ -0,0 +1,90 @@ +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..323a467 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2016 Jake Conway + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..f2788b7 --- /dev/null +++ b/README.rst @@ -0,0 +1,24 @@ +chicagotransit +============== + +A collection of wrappers to communicate with various chicago transit APIs and infosources. + +Installation +------------ + +To install, use ``pip install chicagotransit`` + +Currently Supported +------------------- + +- CTA Bustracker (Bustime) + +Future Expansion +---------------- + +- CTA Traintracker +- Divvy Bikes (WIP) +- Pace Busses* +- Metrarail* + +* if some sort of public API can be found \ No newline at end of file diff --git a/chicagotransit/cta.py b/chicagotransit/cta.py new file mode 100644 index 0000000..9eb6361 --- /dev/null +++ b/chicagotransit/cta.py @@ -0,0 +1,157 @@ +import datetime +import errors +import requests +import xmltodict + +_base_url = 'http://www.ctabustracker.com/bustime/api/v1/' + +class BusTracker(object): + + def __init__(self, key): + self.key = key + + def _time_translation(time_str): + year = int(time_str[0:4]) + month = int(time_str[4:6]) + day = int(time_str[6:8]) + hour = int(time_str[9:11]) + minute = int(time_str[12:14]) + second = int(time_str[15:17]) + time = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second) + return time + + def time(self): + url = _base_url + 'gettime' + result = requests.get(url, params={'key':self.key}) + xml = xmltodict.parse(result.text) + if 'tm' in xml['bustime-response'].keys(): + time_str = xml['bustime-response']['tm'] + return BusTracker._time_translation(time_str) + else: + error = xml['bustime-response']['error']['msg'] + errors.error_handler(error) + + def bus_by_id(self, vid): + url = _base_url + 'getvehicles' + result = requests.get(url, params={'key':self.key, 'vid':vid}) + xml = xmltodict.parse(result.text) + if 'vehicle' in xml['bustime-response'].keys(): + v_data = xml['bustime-response']['vehicle'] + time = v_data['tmstmp'] + latitude = v_data['lat'] + longitude = v_data['lon'] + heading = v_data['hdg'] + pattern_id = v_data['pid'] + route = v_data['rt'] + destination = v_data['des'] + pattern_dist = v_data['pdist'] + speed = v_data['spd'] + bus = BusTracker.Bus(vid, self, time, latitude, longitude, heading, pattern_id, pattern_dist, route, destination, speed) + return bus + else: + error = xml['bustime-response']['error']['msg'] + errors.error_handler(error) + + def routes(self, update=False): + if hasattr(self, 'bus_routes') and self.bus_routes != [] and update == False: + return self.bus_routes + url = _base_url + 'getroutes' + result = requests.get(url, params={'key':self.key}) + xml = xmltodict.parse(result.text) + if 'error' in xml['bustime-response'].keys(): + errors.error_handler(xml['bustime-response']['error']['msg']) + self.bus_routes = [] + for resp in xml['bustime-response']['route']: + self.bus_routes.append(BusTracker.Route(resp['rt'], self, resp['rtnm'])) + return self.bus_routes + + class Bus(object): + def __init__(self, id, bt, time, latitude, longitude, heading, pattern_id, pattern_dist, route, destination, speed, delayed=False): + self.id = id + self.bt = bt + self.time = time + self.latitude = latitude + self.longitude = longitude + self.heading = heading + self.pattern_id = pattern_id + self.pattern_dist = pattern_dist + self.route = route + self.destination = destination + self.delayed = delayed + self.speed = speed + + def update(self): + self = self.bt.bus_by_id(id) + + def __str__(self): + return "id: {0}, rt {1}".format(self.id, self.route) + + class Route(object): + def __init__(self, number, bt, description): + self.number = number + self.bt = bt + self.description = description + + def __str__(self): + return str(self.number) + + def busses(self, update=False): + url = _base_url + 'getvehicles' + result = requests.get(url, params={'key':self.bt.key, 'rt':self.number}) + xml = xmltodict.parse(result.text) + if 'vehicle' in xml['bustime-response'].keys(): + for resp in xml['bustime-response']: + vid = resp['vid'] + time = resp['tmstmp'] + latitude = resp['lat'] + longitude = resp['lon'] + heading = resp['hdg'] + pattern_id = resp['pid'] + route = resp['rt'] + destination = resp['des'] + pattern_dist = resp['pdist'] + speed = resp['spd'] + bus = BusTracker.Bus(vid, self, time, latitude, longitude, heading, pattern_id, pattern_dist, route, destination, speed) + self.busses.append(bus) + else: + error = xml['bustime-response']['error']['msg'] + errors.error_handler(error) + + def directions(self, update=False): + if hasattr(self, 'direction') and not update: + return self.direction + else: + self.direction = [] + url = _base_url + 'getdirections' + result = requests.get(url, params={'key':self.bt.key, 'rt':self.number}) + xml = xmltodict.parse(result.text) + self.direction = xml['bustime-response']['dir'] + return self.direction + + def stops(self, direction, update=False): + assert(direction in self.directions()) + url = _base_url + 'getstops' + result = requests.get(url, params={'key':self.bt.key, 'rt':self.number, 'dir':direction}) + xml = xmltodict.parse(result.text) + if hasattr(self, 'stop') and not update: + return self.stops + elif 'stop' in xml['bustime-response'].keys(): + self.stop = [] + for resp in xml['bustime-response']['stop']: + id = resp['stpid'] + name = resp['stpnm'] + latitude = resp['lat'] + longitude = resp['lon'] + self.stop.append(BusTracker.Stop(id, name, latitude, longitude, self.bt)) + return self.stop + else: + error = xml['bustime-response']['error']['msg'] + errors.error_handler(error) + + class Stop(object): + def __init__(self, id, name, latitude, longitude, bt): + self.id = id + self.name = name + self.latitude = latitude + self.longitude = longitude + self.bt = bt \ No newline at end of file diff --git a/chicagotransit/errors.py b/chicagotransit/errors.py new file mode 100644 index 0000000..229bfd4 --- /dev/null +++ b/chicagotransit/errors.py @@ -0,0 +1,13 @@ +def error_handler(exception): + if exception == 'Invalid API access key supplied': + raise InvalidKeyException + elif exception == 'No data found for parameter': + raise NoDataFoundException + else: + raise Exception(exception) + +class InvalidKeyException(Exception): + pass + +class NoDataFoundException(Exception): + pass \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..30f080b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +xmltodict==0.10.2 +requests \ No newline at end of file diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..e69de29 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..2933c03 --- /dev/null +++ b/setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages +from codecs import open +from os import path + +here = path.abspath(path.dirname(__file__)) +with open(path.join(here, 'README.rst'), encoding='utf-8') as f: + long_description = f.read() + +with open('requirements.txt') as f: + requirements = f.read().splitlines() + +setup( + name='chicagotransit', + version='0.1.0', + description='A package for interfacing with Chicago Transit APIs', + long_description=long_description, + url='https://github.com/conway/ChicagoTransit', + author='Jake Conway', + author_email='jake.h.conway@gmail.com', + license='MIT', + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Topic :: Utilities', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Natural Language :: English' + ], + keywords=['chicago', 'transit', 'wrapper', 'bus', 'train', 'cta', 'divvy'], + packages=find_packages(exclude=['contrib', 'docs', 'tests']), + install_requires=requirements, +) \ No newline at end of file