forked from jonthornton/MTAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
128 lines (108 loc) · 3.14 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# coding: utf-8
"""
mta-api-sanity
~~~~~~
Expose the MTA's real-time subway feed as a json api
:copyright: (c) 2014 by Jon Thornton.
:license: BSD, see LICENSE for more details.
"""
import mta_realtime
from flask import Flask, request, jsonify, render_template, abort
from flask.json import JSONEncoder
from datetime import datetime
from functools import wraps
import logging
app = Flask(__name__)
app.config.update(
MAX_TRAINS=10,
MAX_MINUTES=30,
CACHE_SECONDS=60,
THREADED=True
)
app.config.from_envvar('MTA_SETTINGS')
# set debug logging
if app.debug:
logging.basicConfig(level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
try:
if isinstance(obj, datetime):
return obj.isoformat()
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
app.json_encoder = CustomJSONEncoder
mta = mta_realtime.MtaSanitizer(
app.config['MTA_KEY'],
app.config['STATIONS_FILE'],
max_trains=app.config['MAX_TRAINS'],
max_minutes=app.config['MAX_MINUTES'],
expires_seconds=app.config['CACHE_SECONDS'],
threaded=app.config['THREADED'])
def cross_origin(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = f(*args, **kwargs)
if app.config['DEBUG']:
resp.headers['Access-Control-Allow-Origin'] = '*'
elif 'CROSS_ORIGIN' in app.config:
resp.headers['Access-Control-Allow-Origin'] = app.config['CROSS_ORIGIN']
return resp
return decorated_function
@app.route('/')
@cross_origin
def index():
return jsonify({
'title': 'MtaSanitizer',
'readme': 'Visit https://github.com/jonthornton/MtaSanitizer for more info'
})
@app.route('/by-location', methods=['GET'])
@cross_origin
def by_location():
try:
location = (float(request.args['lat']), float(request.args['lon']))
except KeyError as e:
print e
response = jsonify({
'error': 'Missing lat/lon parameter'
})
response.status_code = 400
return response
return jsonify({
'updated': mta.last_update(),
'data': mta.get_by_point(location, 5)
})
@app.route('/by-route/<route>', methods=['GET'])
@cross_origin
def by_route(route):
try:
return jsonify({
'updated': mta.last_update(),
'data': mta.get_by_route(route)
})
except KeyError as e:
abort(404)
@app.route('/by-id/<id_string>', methods=['GET'])
@cross_origin
def by_index(id_string):
ids = [ int(i) for i in id_string.split(',') ]
try:
return jsonify({
'updated': mta.last_update(),
'data': mta.get_by_id(ids)
})
except KeyError as e:
abort(404)
@app.route('/routes', methods=['GET'])
@cross_origin
def routes():
return jsonify({
'updated': mta.last_update(),
'data': mta.get_routes()
})
if __name__ == '__main__':
app.run(use_reloader=False)