Skip to content

Commit

Permalink
Change API
Browse files Browse the repository at this point in the history
  • Loading branch information
stlk committed Jan 5, 2020
1 parent e554539 commit 2131b46
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
10 changes: 6 additions & 4 deletions api/departures.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@
order by departure_time;
"""

def convert(item):
return (item[0], item[1], str(item[2]), item[3])
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]


@app.route("/api/departures", methods=["GET"])
def api():
Expand All @@ -51,9 +54,8 @@ def api():
cursor = connection.cursor()
try:
cursor.execute(QUERY, {"location": f"POINT({longitude} {latitude})"})
data = cursor.fetchall()
data = dictfetchall(cursor)
finally:
cursor.close()
connection.close()
data = [convert(item) for item in data]
return jsonify(data)
10 changes: 10 additions & 0 deletions app_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,19 @@
from flask import Flask
from request_logger import attach_logger

from datetime import timedelta
import json

class TimeDeltaEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, timedelta):
return str(o)

return json.JSONEncoder.default(self, o)

def create_app():
app = Flask(__name__)
app.json_encoder = TimeDeltaEncoder

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
Expand Down
4 changes: 2 additions & 2 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ function HomePage() {
{departures.loading && <div>...</div>}
{departures.error && <div>Error: {departures.error.message}</div>}
{departures.result
? Object.entries(groupBy(departures.result, 3)).map(([key,group]) => (
? Object.entries(groupBy(departures.result, 'stop_name')).map(([key,group]) => (
<div key={key}>
<h4>{key}</h4>
{group.filter(([route_short_name, trip_headsign, departure_time, stop_name])=> trip_headsign !== stop_name).map(([route_short_name, trip_headsign, departure_time, stop_name]) =>(
{group.filter(({route_short_name, trip_headsign, departure_time, stop_name})=> trip_headsign !== stop_name).map(({route_short_name, trip_headsign, departure_time, stop_name}) =>(
<p key={route_short_name + stop_name + departure_time}>
<em>{route_short_name} - {trip_headsign}</em> {departure_time}
</p>
Expand Down

0 comments on commit 2131b46

Please sign in to comment.