views.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import json
  2. from datetime import datetime
  3. from django.shortcuts import render
  4. from django.http import JsonResponse, HttpResponse
  5. from django.views import View
  6. from django.contrib.auth.decorators import permission_required
  7. from django.contrib.auth.mixins import PermissionRequiredMixin
  8. from .models import *
  9. from pprint import pprint
  10. def index(request):
  11. return render(request, 'gps_logger/index.html')
  12. @permission_required("gps-logger.markers.change")
  13. def upload(request):
  14. return render(request, 'gps_logger/upload.html')
  15. class MarkerCreateView(View, PermissionRequiredMixin):
  16. permission_required = ("gps-logger.markers.change")
  17. def post(self, request):
  18. status_code = 204
  19. data = json.loads(request.body)
  20. for file in data:
  21. if len(data[file]) == 0:
  22. continue
  23. objects = [Marker(
  24. timestamp=datetime.strptime(x['timestamp'].replace("Z","-0000"), r"%Y-%m-%dT%H:%M:%S.%f%z"),
  25. lat = x['lat'],
  26. lng = x['lng'],
  27. alt = x['alt'],
  28. hdop = x.get('hdop', None),
  29. speed = x.get('speed', None)
  30. ) for x in data[file]]
  31. start_date = objects[0].timestamp
  32. end_date = objects[-1].timestamp
  33. oldMarkers = Marker.objects.filter(timestamp__range=(start_date, end_date)).all()
  34. identical = len(oldMarkers) == len(objects)
  35. if identical:
  36. for i, marker in enumerate(oldMarkers):
  37. if marker.timestamp != objects[i].timestamp:
  38. print(type(marker.timestamp), type(objects[i].timestamp))
  39. identical = False
  40. break
  41. print(len(oldMarkers), len(objects), identical)
  42. if not identical:
  43. oldMarkers.delete()
  44. Marker.objects.bulk_create(objects)
  45. status_code = 201
  46. return HttpResponse(status=status_code)
  47. class MarkerView(View):
  48. def get(self, request):
  49. return JsonResponse(list(Marker.objects.values()), safe=False)