option to output route as JSON

This commit is contained in:
Laura Klünder 2016-12-29 20:06:57 +01:00
parent 7cf59dab23
commit 1ab447bbf0
2 changed files with 32 additions and 0 deletions

View file

@ -1,3 +1,5 @@
from collections import OrderedDict
import copy
import numpy as np
@ -18,6 +20,12 @@ class Route:
self.routeparts = None
def serialize(self):
return OrderedDict((
('distance', float(self.distance)),
('routeparts', [routepart.serialize() for routepart in self.routeparts]),
))
def __repr__(self):
return ('<Route (\n %s\n) distance=%f>' %
('\n '.join(repr(connection) for connection in self.connections), self.distance))
@ -227,6 +235,12 @@ class RoutePart:
self.level = graphlevel.level
self.lines = lines
def serialize(self):
return OrderedDict((
('level', self.level.name),
('lines', [line.serialize() for line in self.lines]),
))
def render_svg_coordinates(self):
svg_width, svg_height = get_dimensions()
@ -283,6 +297,17 @@ class RouteLine:
self.title = None
self.description = None
def serialize(self):
return OrderedDict((
('from_point', tuple(self.from_point.xy)),
('to_point', tuple(self.to_point.xy)),
('distance', float(self.distance)),
('icon', self.icon),
('ignore', self.ignore),
('title', self.title),
('description', self.description),
))
class NoRoute:
distance = np.inf

View file

@ -3,6 +3,7 @@ from datetime import timedelta
import qrcode
from django.core.files import File
from django.http import Http404, HttpResponse, HttpResponseNotModified
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
@ -216,6 +217,12 @@ def main(request, location=None, origin=None, destination=None):
route.describe(allowed_ctypes)
ctx.update({'route': route})
if request.GET.get('format') == 'json':
if 'error' in ctx:
return JsonResponse({'error': ctx['error']})
if 'route' in ctx:
return JsonResponse({'route': ctx['route'].serialize()})
response = render(request, 'site/main.html', ctx)
if request.method == 'POST' and save_settings: