-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
276 lines (225 loc) · 7.09 KB
/
__init__.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
https://indego.ericoc.com
https://github.com/ericoc/indego.ericoc.com
__init__.py
"""
from datetime import datetime, timedelta
from flask import (
Flask, flash, g, make_response, render_template, redirect, request,
send_from_directory, url_for
)
from sqlalchemy import extract, func, or_, text
from database import db_session
from models import Indego
# Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')
# Error handlers
def _error(message=None, category=None, code=500):
"""
Handle errors with flash message and response code.
"""
if not message:
message = 'Sorry, but there was an unknown error.'
if not category:
category = 'warn'
flash(message, category)
return render_template('index.html.j2'), code
@app.errorhandler(404)
def _page_not_found(message):
"""
Page Not Found (404 error handler).
"""
return _error(message=message, code=404)
@app.before_request
def pre():
"""
Get latest added time, and current time, before request.
"""
g.latest_added = _latest_added()
g.now = datetime.now()
def _latest_added():
"""
Latest added timestamp where station data is not null.
"""
return db_session.query(
func.max(Indego.added)
).filter(
Indego.data is not None
).first()[0]
def _fetch_chart_data(kiosk_id=None):
"""
Retrieve historical bicycle availability data from PostgreSQL,
to generate JavaScript chart data for a single station.
"""
return db_session.query(
(extract('epoch', Indego.added)*1000).label('added'),
text("station->'properties'->>'bikesAvailable' \"bikesAvailable\"")
).select_from(
Indego,
func.jsonb_array_elements(
Indego.data['features']
).alias('station')
).filter(
Indego.data is not None,
Indego.added >= g.now - timedelta(days=30),
text(f"station->'properties'->>'kioskId' = '{kiosk_id}'")
).order_by('added').all()
def _find_stations(search=None, _field=None):
"""
Find stations from the latest added database row.
"""
# Base query to get stations from the JSON PostgreSQL data
base_query = db_session.query(
text("station->'properties' \"properties\"")
).select_from(
Indego,
func.jsonb_array_elements(Indego.data['features']).alias('station')
).filter_by(
added=g.latest_added
)
final_query = base_query
# Perform any search requested
if search:
final_query = base_query.filter(
_station_filter(search=search, field=_field)
)
# Execute the query
results = final_query.all()
# Create a stations list containing station dictionary items
stations = []
for result in results:
for station in result:
stations.append(station)
# Return the list of station dictionaries
return stations
def _station_filter(search=None, field=None):
"""
Query filter to search stations.
"""
# Get length of numeric searches
if not field and search.isnumeric():
length = len(search)
# Treat four (4) digits as kioskID
if length == 4:
field = 'kioskId'
# Treat five (5) digits as zip code
if length == 5:
field = 'addressZipCode'
# Filter by a specific station field value, if requested
if field:
return text(f"station->'properties'->>'{field}' = '{search}'")
# Search the name and addressStreet fields for the string
if search.isalnum():
return or_(
text(
f"station->'properties'->>'name' ILIKE '%%{search}%%'"
),
text(
f"station->'properties'->>'addressStreet' ILIKE '%%{search}%%'"
)
)
return None
@app.route("/", methods=["GET"])
def index():
"""
Main page returns all stations.
"""
return search_stations(search=None)
@app.route("/search/", methods=["POST"])
def search_form():
"""
Search form.
"""
return redirect(
url_for(
"search_stations",
search=request.form["indego-search"]
)
)
@app.route("/search/", methods=["GET"])
@app.route("/search/<path:search>/", methods=["GET"])
def search_stations(search=None):
"""
Search stations.
"""
stations = _find_stations(search=search)
if stations:
added_web = g.latest_added.astimezone(app.config["TZ"])
added_since = g.now.astimezone(app.config["TZ"]) - added_web
resp = make_response(
render_template(
"index.html.j2",
added_since=added_since,
added_web=added_web,
stations=stations
)
)
resp.headers.set("X-Station-Count", str(len(stations)))
return resp
return _page_not_found("Sorry, but no stations were found!")
@app.route("/chart/<string:chart_string>/", methods=["GET"])
def chart_station(chart_string=None):
"""
Show charts of historical bicycle availability for stations.
Shown within pop-up for a single station, from the main index page.
Also works at /chart/<string> (i.e. /chart/Broad), though not obvious.
"""
chart_stations = _find_stations(search=chart_string)
if chart_stations:
return render_template(
"chart.html.j2",
chart_stations=chart_stations,
chart_string=chart_string
)
return _page_not_found("Sorry, but no stations were found!")
@app.route("/chartjs/<string:chartjs_string>.js", methods=["GET"])
def chartjs_station(chartjs_string=None):
"""
JavaScript for a chart, or multiple charts.
"""
chartjs_stations = _find_stations(search=chartjs_string)
if chartjs_stations:
resp = make_response(
render_template(
"chart.js.j2",
chartjs_stations=chartjs_stations
)
)
resp.headers["Content-Type"] = "text/javascript"
return resp
return _page_not_found("Sorry, but no stations were found!")
@app.route("/chartdata/<int:kiosk_id>.js", methods=["GET"])
def chartdata_station(kiosk_id=None):
"""
JavaScript using PostgreSQL data for charts, for one station.
"""
chartdata_result = _find_stations(search=kiosk_id, _field="kioskId")[0]
if chartdata_result:
resp = make_response(
render_template(
"chartdata.js.j2",
station=chartdata_result,
chart_data=_fetch_chart_data(kiosk_id=kiosk_id)
)
)
resp.headers["Content-Type"] = "text/javascript"
return resp
return _page_not_found("Sorry, but no stations were found!")
@app.route("/favicon.ico", methods=["GET"])
@app.route("/icon.png", methods=["GET"])
def static_from_root():
"""
Static content.
"""
return send_from_directory(app.static_folder, request.path[1:])
@app.teardown_appcontext
def shutdown_session(err=None):
"""
Remove database session at request teardown.
"""
db_session.remove()
if err:
raise err
if __name__ == "__main__":
app.run(debug=app.config['DEBUG'])