/
views.py
860 lines (694 loc) · 32 KB
/
views.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
from __future__ import division
from collections import defaultdict
from itertools import chain
import simplejson
import copy
import math
from datetime import datetime, timedelta
from urllib import unquote
from suds import WebFault
from django.contrib.gis.geos import Point
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.template.defaultfilters import capfirst
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.contrib.gis.measure import D
from molly.utils.views import BaseView, ZoomableView
from molly.utils.breadcrumbs import *
from molly.favourites.views import FavouritableView
from molly.geolocation.views import LocationRequiredView
from molly.maps import Map
from molly.maps.osm.models import OSMUpdate
from molly.apps.places.models import Entity, EntityType, Route, Journey
from molly.apps.places import get_entity, get_point
from molly.apps.places.forms import UpdateOSMForm
class IndexView(BaseView):
def get_metadata(self, request):
return {
'title': _('places'),
'additional': _('Find University buildings and units, along with bus stops and local amenities'), }
@BreadcrumbFactory
def breadcrumb(self, request, context):
return Breadcrumb(
'places',
None,
_('Places'),
lazy_reverse('index'))
def initial_context(self, request):
return {
'return_url': request.get_full_path(),
}
def handle_GET(self, request, context):
return self.render(request, context, 'places/index')
class NearbyListView(LocationRequiredView):
def get_metadata(self, request, entity=None):
return {
'title': _('Find things nearby'),
'additional': _('Search for things based on your current location'),
}
@BreadcrumbFactory
def breadcrumb(self, request, context, entity=None):
return Breadcrumb(
'places',
lazy_parent('index'),
_('Things nearby'),
url = lazy_reverse('nearby-list'),
)
def handle_GET(self, request, context, entity=None):
point = get_point(request, entity)
if point is None:
return self.render(request, { 'entity': entity },
'places/entity_without_location')
if entity:
return_url = reverse('places:entity-nearby-list',
args=[entity.identifier_scheme, entity.identifier_value])
else:
return_url = reverse('places:nearby-list')
# Get entity types to show on nearby page
entity_types = EntityType.objects.filter(show_in_nearby_list=True)
for et in entity_types:
# For each et, get the entities that belong to it
et.max_distance = 0
et.entities_found = 0
es = et.entities_completion.filter(location__isnull=False,
location__distance_lt=(point, D(km=5))).distance(point).order_by('distance')
for e in es:
# Selection criteria for whether or not to count this entity
if (e.distance.m ** 0.75) * (et.entities_found + 1) > 500:
break
et.max_distance = e.distance.m
et.entities_found += 1
categorised_entity_types = defaultdict(list)
for et in filter(lambda et: et.entities_found > 0, entity_types):
categorised_entity_types[_(et.category.name)].append(et)
# Need to do this other Django evalutes .items as ['items']
categorised_entity_types = dict(categorised_entity_types.items())
context.update({
'entity_types': categorised_entity_types,
'entity': entity,
'return_url': return_url,
# entity is None => we've searched around the user's location
'exposes_user_data': entity is None,
})
if entity and not entity.location:
return self.render(request, context, 'places/entity_without_location')
return self.render(request, context, 'places/nearby_list')
class NearbyDetailView(LocationRequiredView, ZoomableView):
def initial_context(self, request, ptypes, entity=None):
point = get_point(request, entity)
entity_types = tuple(get_object_or_404(EntityType, slug=t) for t in ptypes.split(';'))
if point:
entities = Entity.objects.filter(location__isnull = False, is_sublocation = False)
for et in entity_types:
entities = entities.filter(all_types_completion=et)
entities = entities.distance(point).order_by('distance')[:99]
else:
entities = []
context = super(NearbyDetailView, self).initial_context(request, ptypes, entities)
context.update({
'entity_types': entity_types,
'point': point,
'entities': entities,
'entity': entity,
# entity is None => point is the user's location
'exposes_user_data': entity is None,
})
return context
@BreadcrumbFactory
def breadcrumb(self, request, context, ptypes, entity=None):
title = NearbyDetailView.get_metadata(self, request, ptypes, entity)['title']
return Breadcrumb('places',
lazy_parent('nearby-list'),
title,
lazy_reverse('nearby-detail', args=[ptypes]))
def get_metadata(self, request, ptypes, entity=None):
context = NearbyDetailView.initial_context(self, request, ptypes, entity)
if len(context['entity_types']) == 0:
return {
'exclude_from_search': True,
'title': _('Things near %(title)s') % {'title': entity.title}
}
et_name = capfirst(context['entity_types'][0].verbose_name_plural)
if entity is not None:
title = _('%(entity_type)s near %(entity)s') % {
'entity_type':et_name,
'title': entity.title
}
else:
title = _('%(et)s nearby') % {'et': et_name}
if len(context['entity_types']) > 1:
return {
'exclude_from_search': True,
'title': title}
number = len([e for e in context['entities'] if e.location.transform(27700, clone=True).distance(context['point'].transform(27700, clone=True)) <= 1000])
entity_type = context['entity_types'][0].verbose_name_plural
return {
'title': title,
'additional': _('<strong>%(number)d %(entity_type)s</strong> within 1km') % {'number': number,
'entity_type': entity_type}
}
def handle_GET(self, request, context, ptypes, entity=None):
entity_types, entities, point = (
context['entity_types'], context['entities'],
context['point'],
)
if entity and not point:
context = {'entity': entity}
return self.render(request, context, 'places/entity_without_location')
if context['zoom'] is None:
min_points = 5
else:
min_points = 0
entity_map = Map(
centre_point = (point[0], point[1], 'green', ''),
points = [(e.location[0], e.location[1], 'red', e.title)
for e in entities],
min_points = min_points,
zoom = context['zoom'],
width = request.map_width,
height = request.map_height,
)
entities = [[entities[i] for i in b] for a, b in entity_map.points]
found_entity_types = set()
for e in chain(*entities):
e.bearing = e.get_bearing(point)
found_entity_types |= set(e.all_types.all())
found_entity_types -= set(entity_types)
# If there are no entities, return a 404. This should only happen if URLs are manually formed by user.
if len(entities) == 0:
raise Http404()
context.update({
'entities': entities,
'map': entity_map,
'count': sum(map(len, entities)),
'entity_types': entity_types,
'found_entity_types': found_entity_types,
})
return self.render(request, context, 'places/nearby_detail')
class EntityDetailView(ZoomableView, FavouritableView):
default_zoom = 16
def get_metadata(self, request, scheme, value):
entity = get_entity(scheme, value)
user_location = request.session.get('geolocation:location')
distance, bearing = entity.get_distance_and_bearing_from(user_location)
additional = '<strong>%s</strong>' % capfirst(entity.primary_type.verbose_name)
if distance:
additional += ', ' + _('about %(distance)dm %(bearing)s') % {
'distance': int(math.ceil(distance/10)*10),
'bearing': bearing }
routes = sorted(set(sor.route.service_id for sor in entity.stoponroute_set.all()))
if routes:
additional += ', ' + ungettext('service %(services)s stops here',
'services %(services)s stop here',
len(routes)) % {
'services': ' '.join(routes)
}
return {
'title': entity.title,
'additional': additional,
'entity': entity,
}
def initial_context(self, request, scheme, value):
context = super(EntityDetailView, self).initial_context(request)
entity = get_entity(scheme, value)
associations = []
if hasattr(self.conf, 'associations'):
for association in self.conf.associations:
id_type, id, associated_entities = association
try:
if id in entity.identifiers[id_type]:
associations += [{'type': type, 'entities': [get_entity(ns, value) for ns, value in es]} for type, es in associated_entities]
except (KeyError, Http404):
pass
for entity_group in entity.groups.all():
group_entities = filter(lambda e: e != entity,
Entity.objects.filter(groups=entity_group))
if len(group_entities) > 0:
associations.append({
'type': entity_group.title,
'entities': group_entities,
})
board = request.GET.get('board', 'departures')
if board != 'departures':
board = 'arrivals'
context.update({
'entity': entity,
'train_station': entity, # This allows the ldb metadata to be portable
'board': board,
'entity_types': entity.all_types.all(),
'associations': associations,
})
return context
@BreadcrumbFactory
def breadcrumb(self, request, context, scheme, value):
if request.session.get('geolocation:location'):
parent_view = 'nearby-detail'
else:
parent_view = 'category-detail'
entity = get_entity(scheme, value)
return Breadcrumb(
'places',
lazy_parent(parent_view, ptypes=entity.primary_type.slug),
context['entity'].title,
lazy_reverse('entity', args=[scheme, value]),
)
def handle_GET(self, request, context, scheme, value):
entity = context['entity']
if unquote(entity.absolute_url) != request.path:
return self.redirect(entity.absolute_url, request, 'perm')
entities = []
for association in context['associations']:
entities += association['entities']
for provider in reversed(self.conf.providers):
provider.augment_metadata((entity, ), board=context['board'])
provider.augment_metadata([e for atypes in context['associations'] for e in atypes['entities']], board=context['board'])
return self.render(request, context, 'places/entity_detail')
class EntityUpdateView(ZoomableView):
default_zoom = 16
def get_metadata(self, request, scheme, value):
return {
'exclude_from_search': True,
}
def initial_context(self, request, scheme, value):
return dict(
super(EntityUpdateView, self).initial_context(request),
entity=get_entity(scheme, value),
)
@BreadcrumbFactory
def breadcrumb(self, request, context, scheme, value):
return Breadcrumb(
'places',
lazy_parent('entity', scheme=scheme, value=value),
'Update place',
lazy_reverse('entity-update', args=[scheme, value]))
def handle_GET(self, request, context, scheme, value):
entity = context['entity']
if entity.source.module_name != 'molly.providers.apps.maps.osm':
raise Http404
if request.GET.get('submitted') == 'true':
return self.render(request, context, 'places/update_osm_done')
data = dict((k.replace(':', '__'), v) for (k, v) in entity.metadata['osm']['tags'].items())
form = UpdateOSMForm(data)
context['form'] = form
return self.render(request, context, 'places/update_osm')
def handle_POST(self, request, context, scheme, value):
entity = context['entity'] = get_entity(scheme, value)
if entity.source.module_name != 'molly.providers.apps.maps.osm':
raise Http404
form = UpdateOSMForm(request.POST)
if form.is_valid():
new_metadata = copy.deepcopy(entity.metadata['osm'])
for k in ('name', 'operator', 'phone', 'opening_hours', 'url', 'cuisine', 'food', 'food__hours', 'atm', 'collection_times', 'ref', 'capacity'):
tag_name = k.replace('__', ':')
if tag_name in new_metadata and not form.cleaned_data[k]:
del new_metadata['osm']['tags'][tag_name]
elif form.cleaned_data[k]:
new_metadata['tags'][tag_name] = form.cleaned_data[k]
new_metadata['attrs']['version'] = str(int(new_metadata['attrs']['version'])+1)
osm_update = OSMUpdate(
contributor_name = form.cleaned_data['contributor_name'],
contributor_email = form.cleaned_data['contributor_email'],
contributor_attribute = form.cleaned_data['contributor_attribute'],
entity = entity,
old = simplejson.dumps(entity.metadata),
new = simplejson.dumps(new_metadata),
notes = form.cleaned_data['notes'],
)
osm_update.save()
return self.redirect(
reverse('places:entity-update', args=[scheme, value]) + '?submitted=true',
request)
else:
context['form'] = form
return self.render(request, context, 'places/update_osm')
class NearbyEntityListView(NearbyListView):
def is_location_required(self, request, scheme, value):
return False
def get_metadata(self, request, scheme, value):
entity = get_entity(scheme, value)
return super(NearbyEntityListView, self).get_metadata(request, entity)
def initial_context(self, request, scheme, value):
return {
'entity': get_entity(scheme, value),
}
@BreadcrumbFactory
def breadcrumb(self, request, context, scheme, value):
return Breadcrumb(
'places',
lazy_parent('entity', scheme=scheme, value=value),
'Things near %s' % context['entity'].title,
lazy_reverse('entity-nearby-list', args=[scheme, value]))
def handle_GET(self, request, context, scheme, value):
entity = get_entity(scheme, value)
return super(NearbyEntityListView, self).handle_GET(request, context, entity)
class NearbyEntityDetailView(NearbyDetailView):
def is_location_required(self, request, scheme, value, ptype):
return False
def initial_context(self, request, scheme, value, ptype):
entity = get_entity(scheme, value)
context = super(NearbyEntityDetailView, self).initial_context(request, ptype, entity)
context['entity'] = entity
return context
@BreadcrumbFactory
def breadcrumb(self, request, context, scheme, value, ptype):
entity_type = get_object_or_404(EntityType, slug=ptype)
return Breadcrumb(
'places',
lazy_parent('entity-nearby-list', scheme=scheme, value=value),
'%s near %s' % (
capfirst(entity_type.verbose_name_plural),
context['entity'].title, ),
lazy_reverse('places:entity_nearby_detail', args=[scheme, value, ptype]))
def get_metadata(self, request, scheme, value, ptype):
entity = get_entity(type_slug, id)
return super(NearbyEntityDetailView, self).get_metadata(request, ptype, entity)
def handle_GET(self, request, context, scheme, value, ptype):
entity = get_entity(scheme, value)
return super(NearbyEntityDetailView, self).handle_GET(request, context, ptype, entity)
class CategoryListView(BaseView):
def initial_context(self, request):
categorised_entity_types = defaultdict(list)
for et in EntityType.objects.filter(show_in_category_list=True):
categorised_entity_types[_(et.category.name)].append(et)
# Need to do this other Django evalutes .items as ['items']
categorised_entity_types = dict(categorised_entity_types.items())
return {
'entity_types': categorised_entity_types,
}
@BreadcrumbFactory
def breadcrumb(self, request, context):
return Breadcrumb(
'places',
lazy_parent('index'),
'Categories',
lazy_reverse('category-list'),
)
def handle_GET(self, request, context):
return self.render(request, context, 'places/category_list',
expires=timedelta(days=28))
class CategoryDetailView(BaseView):
def initial_context(self, request, ptypes):
entity_types = tuple(get_object_or_404(EntityType, slug=t) for t in ptypes.split(';'))
entities = Entity.objects.filter(is_sublocation=False)
for entity_type in entity_types:
entities = entities.filter(all_types_completion=entity_type)
entities = sorted(entities, key=lambda e: e.title)
paginator = Paginator(entities, 100)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
paged_entities = paginator.page(page)
except (EmptyPage, InvalidPage):
paged_entities = paginator.page(1)
found_entity_types = set()
for e in entities:
found_entity_types |= set(e.all_types.all())
found_entity_types -= set(entity_types)
return {
'entity_types': entity_types,
'count': len(entities),
'entities': paged_entities,
'found_entity_types': found_entity_types,
}
@BreadcrumbFactory
def breadcrumb(self, request, context, ptypes):
return Breadcrumb(
'places',
lazy_parent('category-list'),
capfirst(context['entity_types'][0].verbose_name_plural),
lazy_reverse('category-detail', args=[ptypes]),
)
def get_metadata(self, request, ptypes):
context = CategoryDetailView.initial_context(self, request, ptypes)
if len(context['entity_types']) > 1:
return {
'exclude_from_search': True,
'title': 'All %s' % context['entity_types'][0].verbose_name_plural,
}
return {
'title': 'All %s' % context['entity_types'][0].verbose_name_plural,
'additional': '<strong>%d %s</strong>' % (
context['entities'].paginator.count,
context['entity_types'][0].verbose_name_plural,
),
}
def handle_GET(self, request, context, ptypes):
return self.render(request, context, 'places/category_detail',
expires=timedelta(days=1))
class ServiceDetailView(BaseView):
"""
A view showing details of a particular transport service leaving from a place
"""
@BreadcrumbFactory
def breadcrumb(self, request, context, scheme, value):
return Breadcrumb(
'places',
lazy_parent('entity', scheme=scheme, value=value),
context['title'],
lazy_reverse('service-detail', args=[scheme, value]))
def get_metadata(self, request, scheme, value):
return {}
def initial_context(self, request, scheme, value):
context = super(ServiceDetailView, self).initial_context(request)
service_id = request.GET.get('id')
route_id = request.GET.get('route')
route_pk = request.GET.get('routeid')
journey = request.GET.get('journey')
if service_id or route_id or route_pk or journey:
entity = get_entity(scheme, value)
else:
raise Http404()
context.update({
'entity': entity,
})
if service_id:
# Add live information from the providers
for provider in reversed(self.conf.providers):
provider.augment_metadata((entity, ))
# If we have no way of getting further journey details, 404
if 'service_details' not in entity.metadata:
raise Http404
# Deal with train service data
if entity.metadata['service_type'] == 'ldb':
# LDB has + in URLs, but Django converts that to space
service = entity.metadata['service_details'](service_id.replace(' ', '+'))
else:
service = entity.metadata['service_details'](service_id)
if service is None:
raise Http404
if 'error' in service:
context.update({
'title': 'An error occurred',
'service': {
'error': service['error'],
},
})
return context
context.update({
'service': service,
'title': service['title'],
'zoom_controls': False,
})
elif route_id or route_pk:
if route_id:
route = entity.route_set.filter(service_id=route_id).distinct()
if route.count() == 0:
raise Http404()
elif route.count() > 1:
context.update({
'title': _('Multiple routes found'),
'multiple_routes': route
})
return context
else:
route = route[0]
else:
route = get_object_or_404(Route, id=route_pk)
i = 1
calling_points = []
previous = True
for stop in route.stoponroute_set.all():
if stop.entity == entity:
previous = False
calling_point = {
'entity': stop.entity,
'at': previous
}
if stop.entity.location is not None:
calling_point['stop_num'] = i
i += 1
calling_points.append(calling_point)
service = {
'entities': route.stops.all(),
'operator': route.operator,
'has_timetable': False,
'has_realtime': False,
'calling_points': calling_points
}
if entity not in service['entities']:
raise Http404()
context.update({
'title': '%s: %s' % (route.service_id, route.service_name),
'service': service
})
elif journey:
journey = get_object_or_404(Journey, id=journey)
route = journey.route
entity_passed = False
i = 1
calling_points = []
for stop in journey.scheduledstop_set.all():
if stop.entity == entity:
entity_passed = True
if not entity_passed and stop.std < datetime.now().time():
calling_point = {
'entity': stop.entity,
'st': stop.std.strftime('%H:%M'),
'at': True
}
else:
calling_point = {
'entity': stop.entity,
# Show arrival time (if it exists, else departure time)
# if this stop is AFTER where we currently are, otherwise
# show the time the bus left stops before this one (if
# it exists)
'st': ((stop.sta or stop.std) if entity_passed else (stop.std or stop.sta)).strftime('%H:%M'),
'at': False
}
if stop.entity.location is not None:
calling_point['stop_num'] = i
i += 1
calling_points.append(calling_point)
service = {
'entities': [s.entity for s in journey.scheduledstop_set.all()],
'operator': journey.route.operator,
'has_timetable': True,
'has_realtime': False,
'calling_points': calling_points,
'notes': journey.notes
}
if entity not in service['entities']:
raise Http404()
context.update({
'title': '%s: %s' % (route.service_id, route.service_name),
'service': service
})
if entity.location or len(filter(lambda e: e.location is not None, service['entities'])):
map = Map(
centre_point = (entity.location[0], entity.location[1],
'green', entity.title) if entity.location else None,
points = [(e.location[0], e.location[1], 'red', e.title)
for e in service['entities'] if e.location is not None],
min_points = len(service['entities']),
zoom = None,
width = request.map_width,
height = request.map_height,
)
context.update({
'map': map
})
return context
def handle_GET(self, request, context, scheme, value):
return self.render(request, context, 'places/service_details')
class APIView(BaseView):
"""
Returns a JSON object containing entity details.
Valid parameters are:
* type: Filters by an EntityType slug
* source: Filters by data source; a places provider module name.
* near: A long,lat pair to order by
* max_distance: Filters out those more than the specified distance from the point given above.
* limit: The number of results to return; defaults to 100; capped at 200 (or 1000 if without_metadata specified)
* offset: The number of results to skip; defaults to 0
* without_metadata: If 'true', metadata aren't returned. Raises the limit cap.
It is an error to specify max_distance without near. Entities are ordered
by name and then DB id; hence the order is deterministic.
Returns a JSON object with the following attributes:
* count: The number of entities that survived the filters
* returned: The number of entities returned once limit and offset were taken into account
* limit: The limit used. This may differ from that provided when the latter was invalid.
* offset: The offset used. This may differ as above.
* entities: A list of entities
Entities are JSON objects with the following attributes:
* primary_type: The primary type of the entity
* all_types: A list containing all types of the object
* source: The data source for the entity, with the same range as given above
* url: The location of this resource on this host
* name: The title of the entity.
* location: A two-element list containing longitude and latitude
* metadata: Any further metadata as provided by the data source
"""
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context):
entities = Entity.objects.order_by('title', 'id')
error = False
without_metadata = request.GET.get('without_metadata') == 'true'
limit, offset = request.GET.get('limit', 100), request.GET.get('offset', 0)
try:
limit, offset = int(limit), int(offset)
except (ValueError, TypeError):
limit, offset = 100, 0
limit, offset = min(limit, 1000 if without_metadata else 200), max(offset, 0)
if 'type' in request.GET:
entities = entities.filter(all_types_completion__slug = request.GET['type'])
if 'source' in request.GET:
entities = entities.filter(source__module_name = request.GET['source'])
if 'near' in request.GET:
try:
point = Point(map(float, request.GET['near'].split(',')), srid=4326).transform(27700, clone=True)
entities = entities.filter(location__isnull=False)
entities = entities.distance(point).order_by('distance')
for entity in entities:
entity.distance = entity.location.transform(27700, clone=True).distance(point)
if 'max_distance' in request.GET:
max_distance = float(request.GET['max_distance'])
new_entities = []
for entity in entities:
if entity.distance > max_distance:
break
new_entities.append(entity)
entities = new_entities
count = len(entities)
if 'limit' in request.GET:
entities = islice(entities, offset, offset+limit)
else:
count = entities.count()
except:
entities, count, error = [], 0, True
elif 'max_distance' in request.GET:
entities, count, error = [], 0, True
if not 'near' in request.GET:
count = entities.count()
try:
entities = entities[offset:offset+limit]
except ValueError:
entities, count, error = [], 0, True
out = []
for entity in entities:
out.append({
'primary_type': entity.primary_type.slug,
'all_types': [et.slug for et in entity.all_types_completion.all()],
'source': entity.source.module_name,
'name': entity.title,
'location': tuple(entity.location) if entity.location else None,
'url': entity.get_absolute_url(),
})
if not without_metadata:
out[-1]['metadata'] = entity.metadata
if 'near' in request.GET:
out[-1]['distance'] = entity.distance
out = {
'offset': offset,
'limit': limit,
'entities': out,
'count': count,
'error': error,
'returned': len(out),
}
return self.render(request, out, None)