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.3 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  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 LabelValidationError
  11. from ..models import Label, Project
  12. from ..permissions import IsInProjectReadOnlyOrAdmin, IsProjectAdmin
  13. from ..serializers import LabelSerializer
  14. class LabelList(generics.ListCreateAPIView):
  15. serializer_class = LabelSerializer
  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.labels
  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. Label.objects.filter(pk__in=delete_ids).delete()
  27. return Response(status=status.HTTP_204_NO_CONTENT)
  28. class LabelDetail(generics.RetrieveUpdateDestroyAPIView):
  29. queryset = Label.objects.all()
  30. serializer_class = LabelSerializer
  31. lookup_url_kwarg = 'label_id'
  32. permission_classes = [IsAuthenticated & IsInProjectReadOnlyOrAdmin]
  33. class LabelUploadAPI(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. labels = json.load(request.data['file'])
  43. serializer = LabelSerializer(data=labels, 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 LabelValidationError