Skip to content
This repository was archived by the owner on Jun 29, 2023. It is now read-only.

Commit 82f283a

Browse files
committed
made pep8 compliant, added non-object-oriented get_departures()
1 parent ee9a0a4 commit 82f283a

1 file changed

Lines changed: 46 additions & 17 deletions

File tree

mvg/__init__.py

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# coding=utf-8
22

3-
import urllib2, json, datetime
3+
import urllib2
4+
import json
5+
import datetime
46
from time import mktime
57

68
api_key = "5af1beca494712ed38d313714d4caff6"
@@ -10,12 +12,14 @@
1012
nearby_url = "https://www.mvg.de/fahrinfo/api/location/nearby"
1113
routing_url = "https://www.mvg.de/fahrinfo/api/routing/?"
1214

15+
1316
def _perform_api_request(url):
1417
opener = urllib2.build_opener()
1518
opener.addheaders = [('X-MVG-Authorization-Key', api_key)]
1619
response = opener.open(url)
1720
return json.loads(response.read())
1821

22+
1923
def _convert_time(time):
2024
"""
2125
Takes datetime.datetime() or unix time in ms
@@ -29,6 +33,7 @@ def _convert_time(time):
2933
except Exception as e:
3034
raise
3135

36+
3237
def get_nearby_stations(lat, log):
3338
if lat == 0 or log == 0:
3439
return None
@@ -41,6 +46,7 @@ def get_nearby_stations(lat, log):
4146
results = _perform_api_request(url)
4247
return results['locations']
4348

49+
4450
def get_id_for_station(station_name):
4551
"""
4652
Gives the station_id for the given station_name.
@@ -50,6 +56,7 @@ def get_id_for_station(station_name):
5056
station = get_stations(station_name)[0]
5157
return station['id']
5258

59+
5360
def get_locations(query):
5461
if isinstance(query, int):
5562
url = query_url + str(query)
@@ -67,11 +74,10 @@ def get_stations(station):
6774
stations.append(result)
6875
return stations
6976

70-
def get_route(start, dest, time=None, arrival_time=False, max_walk_time_to_start=None, max_walk_time_to_dest=None):
71-
"""
72-
returns connectionList = [] of possible routes.
73-
Adds departure_datetime and arrival_datetime to array as datetime objects.
74-
"""
77+
78+
def get_route(start, dest,
79+
time=None, arrival_time=False,
80+
max_walk_time_to_start=None, max_walk_time_to_dest=None):
7581
url = routing_url
7682
options = []
7783

@@ -81,15 +87,17 @@ def get_route(start, dest, time=None, arrival_time=False, max_walk_time_to_start
8187
options.append("fromLatitude=" + str(start[0]))
8288
options.append("fromLongitude=" + str(start[1]))
8389
else:
84-
raise ValueError("A start must be given; either int station id or tuple latitude longitude")
90+
raise ValueError("A start must be given;\
91+
either int station id or tuple latitude longitude")
8592

8693
if isinstance(dest, int):
8794
options.append("toStation=" + str(dest))
8895
elif isinstance(dest, tuple) and len(dest) == 2:
8996
options.append("toLatitude=" + str(dest[0]))
9097
options.append("toLongitude=" + str(dest[1]))
9198
else:
92-
raise ValueError("A destination must be given; either int station id or tuple latitude longitude")
99+
raise ValueError("A destination must be given;\
100+
either int station id or tuple latitude longitude")
93101

94102
if time:
95103
if isinstance(time, datetime.datetime):
@@ -98,30 +106,51 @@ def get_route(start, dest, time=None, arrival_time=False, max_walk_time_to_start
98106
if arrival_time:
99107
options.append("arrival=true")
100108
if max_walk_time_to_start:
101-
options.append("maxTravelTimeFootwayToStation=" + str(max_walk_time_to_start))
109+
options.append("maxTravelTimeFootwayToStation=" +
110+
str(max_walk_time_to_start))
102111
if max_walk_time_to_dest:
103-
options.append("maxTravelTimeFootwayToDestination=" + str(max_walk_time_to_dest))
112+
options.append("maxTravelTimeFootwayToDestination=" +
113+
str(max_walk_time_to_dest))
104114

105115
options_url = "&".join(options)
106116
url = routing_url + options_url
107117
results = _perform_api_request(url)
108118
for connection in results["connectionList"]:
109-
connection["departure_datetime"] = _convert_time(connection["departure"])
119+
connection["departure_datetime"] = \
120+
_convert_time(connection["departure"])
110121
connection["arrival_datetime"] = _convert_time(connection["arrival"])
111122
return results["connectionList"]
112123

113124

125+
def get_departures(station_id):
126+
"""get array of departures for station_id."""
127+
if not isinstance(station_id, int):
128+
raise TypeError("Please give the int station_id of the station.\
129+
You can find it out by running \
130+
get_id_for_station('Station name')")
131+
url = departure_url + str(station_id) + departure_url_postfix
132+
departures = _perform_api_request(url)['departures']
133+
for departure in departures:
134+
# For some reason, mvg gives you a Unix timestamp, but in milliseconds.
135+
# Here, we convert it to datetime
136+
time = _convert_time(departure['departureTime'])
137+
relative_time = time - datetime.datetime.now()
138+
departure[u'departureTimeMinutes'] = relative_time.seconds // 60
139+
return departures
140+
141+
114142
class Station:
115-
"""
116-
Gives you an object to acess current departure times from mvg.de
143+
"""Gives you an object to acess current departure times from mvg.de
144+
Might be useful if you need to keep track of multiple stations?
117145
118-
Either give it an exact station name (like "Hauptbahnhof") or a station_id.
146+
Either give it an exact station name (like "Hauptbahnhof")
147+
or a station_id.
119148
"""
120149

121150
def __init__(self, station):
122151
if isinstance(station, str) or isinstance(station, unicode):
123152
self.station_id = get_id_for_station(station)
124-
if self.station_id == None:
153+
if self.station_id is None:
125154
raise NameError("No matching station found")
126155
elif isinstance(station, int):
127156
self.station_id = station
@@ -137,8 +166,8 @@ def get_departures(self):
137166
url = departure_url + str(self.station_id) + departure_url_postfix
138167
departures = _perform_api_request(url)['departures']
139168
for departure in departures:
140-
# For some reason, mvg gives you a Unix timestamp, but in milliseconds.
141-
# Here, we convert it to datetime
169+
# For some reason, mvg gives you a Unix timestamp in milliseconds.
170+
# Here, we convert it to a datetime object
142171
time = _convert_time(departure['departureTime'])
143172
relative_time = time - datetime.datetime.now()
144173
departure[u'departureTimeMinutes'] = relative_time.seconds // 60

0 commit comments

Comments
 (0)