import json from datetime import datetime from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.views import View from django.contrib.auth.decorators import permission_required from django.contrib.auth.mixins import PermissionRequiredMixin from .models import * from pprint import pprint def index(request): return render(request, 'gps_logger/index.html') @permission_required("gps-logger.markers.change") def upload(request): return render(request, 'gps_logger/upload.html') class MarkerCreateView(View, PermissionRequiredMixin): permission_required = ("gps-logger.markers.change") def post(self, request): status_code = 204 data = json.loads(request.body) for file in data: if len(data[file]) == 0: continue objects = [Marker( timestamp=datetime.strptime(x['timestamp'].replace("Z","-0000"), r"%Y-%m-%dT%H:%M:%S.%f%z"), lat = x['lat'], lng = x['lng'], alt = x['alt'], hdop = x.get('hdop', None), speed = x.get('speed', None) ) for x in data[file]] start_date = objects[0].timestamp end_date = objects[-1].timestamp oldMarkers = Marker.objects.filter(timestamp__range=(start_date, end_date)).all() identical = len(oldMarkers) == len(objects) if identical: for i, marker in enumerate(oldMarkers): if marker.timestamp != objects[i].timestamp: print(type(marker.timestamp), type(objects[i].timestamp)) identical = False break print(len(oldMarkers), len(objects), identical) if not identical: oldMarkers.delete() Marker.objects.bulk_create(objects) status_code = 201 return HttpResponse(status=status_code) class MarkerView(View): def get(self, request): return JsonResponse(list(Marker.objects.values()), safe=False)