You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.5 KiB

  1. import json
  2. from django.db import IntegrityError, transaction
  3. from django.shortcuts import get_object_or_404
  4. from rest_framework import generics, status
  5. from rest_framework.exceptions import ParseError
  6. from rest_framework.parsers import MultiPartParser
  7. from rest_framework.permissions import IsAuthenticated
  8. from rest_framework.response import Response
  9. from rest_framework.views import APIView
  10. from ..exceptions import AnnotationRelationValidationError
  11. from ..models import AnnotationRelations, Project
  12. from ..permissions import IsInProjectReadOnlyOrAdmin, IsProjectAdmin
  13. from ..serializers import AnnotationRelationsSerializer
  14. class AnnotationRelationsList(generics.ListCreateAPIView):
  15. serializer_class = AnnotationRelationsSerializer
  16. pagination_class = None
  17. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  18. def get_queryset(self):
  19. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  20. return project.annotation_relations
  21. def perform_create(self, serializer):
  22. project = get_object_or_404(Project, pk=self.kwargs['project_id'])
  23. serializer.save(project=project)
  24. def delete(self, request, *args, **kwargs):
  25. delete_ids = request.data['ids']
  26. AnnotationRelations.objects.filter(pk__in=delete_ids).delete()
  27. return Response(status=status.HTTP_204_NO_CONTENT)
  28. class AnnotationRelationsDetail(generics.RetrieveUpdateDestroyAPIView):
  29. queryset = AnnotationRelations.objects.all()
  30. serializer_class = AnnotationRelationsSerializer
  31. lookup_url_kwarg = 'annotation_relation_id'
  32. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  33. class AnnotationRelationsUploadAPI(APIView):
  34. parser_classes = (MultiPartParser,)
  35. permission_classes = [IsAuthenticated & IsProjectAdmin]
  36. @transaction.atomic
  37. def post(self, request, *args, **kwargs):
  38. if 'file' not in request.data:
  39. raise ParseError('Empty content')
  40. project = get_object_or_404(Project, pk=kwargs['project_id'])
  41. try:
  42. annotation_relations = json.load(request.data)
  43. serializer = AnnotationRelationsSerializer(data=annotation_relations, many=True)
  44. serializer.is_valid(raise_exception=True)
  45. serializer.save(project=project)
  46. return Response(status=status.HTTP_201_CREATED)
  47. except json.decoder.JSONDecodeError:
  48. raise ParseError('The file format is invalid.')
  49. except IntegrityError:
  50. raise AnnotationRelationValidationError