serializers.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from django.db import IntegrityError
  2. from rest_framework import serializers
  3. from apps.files.models import File
  4. from apps.projects.serializers.base_serializers import ProjectReferenceSerializer
  5. from glitchtip.exceptions import ConflictException
  6. from .models import Release, ReleaseFile
  7. class ReleaseSerializer(serializers.ModelSerializer):
  8. dateCreated = serializers.DateTimeField(source="created", read_only=True)
  9. dateReleased = serializers.DateTimeField(source="released", required=False)
  10. shortVersion = serializers.CharField(source="version", read_only=True)
  11. deployCount = serializers.IntegerField(source="deploy_count", read_only=True)
  12. projects = ProjectReferenceSerializer(many=True, read_only=True)
  13. class Meta:
  14. model = Release
  15. fields = (
  16. "url",
  17. "data",
  18. "deployCount",
  19. "dateCreated",
  20. "dateReleased",
  21. "version",
  22. "shortVersion",
  23. "projects",
  24. )
  25. lookup_field = "version"
  26. class ReleaseFileSerializer(serializers.ModelSerializer):
  27. file = serializers.FileField(write_only=True, allow_empty_file=True)
  28. sha1 = serializers.CharField(source="file.checksum", read_only=True)
  29. dateCreated = serializers.DateTimeField(source="created", read_only=True)
  30. headers = serializers.JSONField(source="file.headers", read_only=True)
  31. size = serializers.IntegerField(source="file.size", read_only=True)
  32. id = serializers.CharField(read_only=True)
  33. class Meta:
  34. model = ReleaseFile
  35. fields = ("sha1", "name", "dateCreated", "headers", "file", "id", "size")
  36. read_only_fields = ("headers",)
  37. extra_kwargs = {"file": {"write_only": True}}
  38. def create(self, validated_data):
  39. fileobj = validated_data.pop("file")
  40. release = validated_data.pop("release")
  41. full_name = validated_data.get("name", fileobj.name)
  42. name = full_name.rsplit("/", 1)[-1]
  43. headers = {"Content-Type": fileobj.content_type}
  44. validated_data["name"] = name
  45. validated_data["headers"] = headers
  46. file = File.objects.create(name=name, headers=headers)
  47. file.putfile(fileobj)
  48. try:
  49. release_file = ReleaseFile.objects.create(
  50. release=release,
  51. file=file,
  52. name=full_name,
  53. )
  54. except IntegrityError:
  55. file.delete()
  56. raise ConflictException("File already present!")
  57. return release_file
  58. class AssembleSerializer(serializers.Serializer):
  59. checksum = serializers.RegexField("^[a-fA-F0-9]+$", max_length=40, min_length=40)
  60. chunks = serializers.ListField(
  61. child=serializers.RegexField("^[a-fA-F0-9]+$", max_length=40, min_length=40)
  62. )