views.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from django.http import JsonResponse, HttpResponseForbidden
  2. from django.views.generic import View
  3. from .models import Contrib
  4. class JSONContribView(View):
  5. def get(self, request):
  6. return JsonResponse({
  7. "id": self.ID,
  8. "license": self.LICENSE,
  9. "features": self.get_features(),
  10. })
  11. PLACE_PROPERTIES = [
  12. 'floor', 'angles', 'orientations', 'roof', 'floor', 'floor_total']
  13. class PublicJSON(JSONContribView):
  14. ID = 'public'
  15. LICENSE = {
  16. "type": "ODC-BY-1.0",
  17. "url": "http:\/\/opendatacommons.org\/licenses\/by\/1.0\/"
  18. }
  19. def get_features(self):
  20. contribs = Contrib.objects.all()
  21. data = []
  22. for i in contribs:
  23. if not i.is_public():
  24. continue
  25. data.append({
  26. "id": i.pk,
  27. "type": "Feature",
  28. "geometry": {
  29. "coordinates": [
  30. i.latitude,
  31. i.longitude,
  32. ],
  33. "type": "Point",
  34. },
  35. "properties": {
  36. "contrib_type": i.contrib_type,
  37. "name": i.get_public_field('name'),
  38. "place": {
  39. k: i.get_public_field(k) for k in self.PLACE_PROPERTIES
  40. },
  41. "comment": i.get_public_field('comment'),
  42. }
  43. })
  44. return data
  45. class PrivateJSON(JSONContribView):
  46. ID = 'private'
  47. LICENSE = {
  48. "type": "Copyright",
  49. }
  50. def dispatch(self, request, *args, **kwargs):
  51. if hasattr(request, 'user') and request.user.is_staff:
  52. return super().dispatch(request, *args, **kwargs)
  53. else:
  54. return HttpResponseForbidden('Need staff access')
  55. def get_features(self):
  56. contribs = Contrib.objects.all()
  57. data = []
  58. for i in contribs:
  59. if not i.is_public():
  60. continue
  61. data.append({
  62. "id": i.pk,
  63. "type": "Feature",
  64. "geometry": {
  65. "coordinates": [
  66. i.latitude,
  67. i.longitude,
  68. ],
  69. "type": "Point",
  70. },
  71. "properties": {
  72. "contrib_type": i.contrib_type,
  73. "name": i.name,
  74. "place": {
  75. k: getattr(i, k) for k in self.PLACE_PROPERTIES
  76. },
  77. "comment": i.comment,
  78. "phone": i.phone,
  79. "email": i.email
  80. }
  81. })
  82. return data