74 lines
2.9 KiB
Python
74 lines
2.9 KiB
Python
"""
|
|
Views
|
|
=====
|
|
Views reacting to Http Requests by interfacing between backend and frontend.
|
|
|
|
Functions
|
|
---------
|
|
index(request)
|
|
Home page
|
|
"""
|
|
from django.shortcuts import render
|
|
from django.http import HttpResponse, HttpRequest
|
|
from .models import *
|
|
from .forms import *
|
|
import json
|
|
from datetime import datetime
|
|
|
|
def get_timetable(r, trips, stop_sequences):
|
|
"""
|
|
Given a pt_map.models.Route, calculate the timetable for all its stops.
|
|
|
|
Parameters
|
|
----------
|
|
r : pt_map.models.Route
|
|
Route, the timetable should be calculated for
|
|
trips : dict(str, list(pt_map.Trip))
|
|
Dictionary mapping all trips to route_ids they travel on
|
|
stop_sequences : dict(str, list(str))
|
|
Dict mapping route_ids to lists of stop_ids they serve. Currently the first trip is taken as reference for stops and sequence.
|
|
|
|
Returns
|
|
-------
|
|
dict{"stop_sequence": list(str), "stop_times": dict(str, list(str)}
|
|
Dict containing two elements:
|
|
"stop_sequence" : list(str)
|
|
list of stop_ids the route serves
|
|
"stop_times" : dict(str, list(str))
|
|
dict mapping stop_ids from stop_sequence to time strings the route is serving the stop at
|
|
"""
|
|
timetable = {"stop_sequence": stop_sequences[r.route_id]}
|
|
sts = {}
|
|
for stop in stop_sequences[r.route_id]:
|
|
times = []
|
|
for t in trips[r.route_id]:
|
|
for st in StopTime.objects.filter(trip_id=t.trip_id):
|
|
times.append(st.departure_time.strftime("%H:%M"))
|
|
sts[stop] = times
|
|
timetable["stop_times"] = sts
|
|
return timetable
|
|
|
|
|
|
def index(request):
|
|
stops = {s.stop_id: {name: getattr(s, name) for name in ['stop_name', 'stop_lat', 'stop_lon']} for s in Stop.objects.all()}
|
|
route_name = lambda r : r.route_short_name if r.route_short_name else r.route_long_name
|
|
routes = [{"route_id": r.route_id, "route_type": r.route_type, "route_name": route_name(r), "agency_id": r.agency_id.agency_id} for r in Route.objects.all()]
|
|
trips = {r["route_id"]: [t for t in Trip.objects.filter(route_id_id=r["route_id"])] for r in routes}
|
|
stop_sequences = {}
|
|
for r in routes:
|
|
seq = []
|
|
t = trips[r["route_id"]]
|
|
for s in StopTime.objects.filter(trip_id_id__exact=t[0].trip_id):
|
|
seq.append(s)
|
|
stop_sequences[r["route_id"]] = [s.stop_id.stop_id for s in sorted(seq, key=lambda st : st.stop_sequence)]
|
|
timetable = {}
|
|
if request.GET.get("timetable"):
|
|
try:
|
|
r = Route.objects.get(route_id=request.GET.get("timetable"))
|
|
timetable = get_timetable(r, trips, stop_sequences)
|
|
except Route.DoesNotExist:
|
|
print(f"Invalid request for Route with id {request.GET['timetable']}")
|
|
context = {"stops": json.dumps(stops), "routes": json.dumps(routes), "timetable": json.dumps(timetable)}
|
|
return render(request,"map.html", context)
|
|
|