Skip to content

Serializers

S3ConfigSerializer

Bases: Serializer

Serializer to represent s3 config.

Source code in saritasa_s3_tools/django/serializers.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
class S3ConfigSerializer(serializers.Serializer):
    """Serializer to represent s3 config."""

    name = serializers.CharField()
    allowed = serializers.ListField(
        child=serializers.CharField(),
        allow_null=True,
    )
    content_length_range = serializers.ListField(
        child=serializers.CharField(),
        allow_null=True,
    )
    expires_in = serializers.IntegerField()
    success_action_status = serializers.IntegerField()
    content_disposition = serializers.CharField()

S3FieldsConfigMixin

Extend serializer_field_mapping with s3 fields.

Deprecate it once encode/django-rest-framework#9507 is accepted.

Source code in saritasa_s3_tools/django/serializers.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class S3FieldsConfigMixin:
    """Extend serializer_field_mapping with s3 fields.

    Deprecate it once encode/django-rest-framework#9507 is accepted.

    """

    @property
    def serializer_field_mapping(
        self,
    ) -> dict[type[models.Field], type[serializers.Field]]:
        """Extend serializer mapping with s3 fields."""
        serializer_field_mapping = super().serializer_field_mapping  # type: ignore
        serializer_field_mapping[models.FileField] = (
            drf_fields.S3UploadURLField
        )
        serializer_field_mapping[models.ImageField] = (
            drf_fields.S3UploadURLField
        )
        return serializer_field_mapping

serializer_field_mapping property

Extend serializer mapping with s3 fields.

S3ParamsSerializer

Bases: Serializer

Serializer for showing params for s3 upload.

Source code in saritasa_s3_tools/django/serializers.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class S3ParamsSerializer(serializers.Serializer):
    """Serializer for showing params for s3 upload."""

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
        fields = getattr(
            settings,
            "SARITASA_S3_TOOLS_UPLOAD_PARAMS",
            constants.s3v4_signature_fields,
        )
        for field in fields:
            self.fields[field] = serializers.CharField(
                label=field,
                required=False,
                allow_null=True,
            )

S3RequestParamsSerializer

Bases: Serializer

Serializer for validation s3 uploading fields.

Source code in saritasa_s3_tools/django/serializers.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class S3RequestParamsSerializer(serializers.Serializer):
    """Serializer for validation s3 uploading fields."""

    config = drf_fields.S3FileTypeConfigField()
    filename = serializers.CharField()
    content_type = serializers.CharField()
    content_length = serializers.IntegerField()

    def __init__(
        self,
        context_request: request.Request | None = None,
        *args,  # noqa: ANN002
        **kwargs,
    ) -> None:
        """Set current user."""
        super().__init__(*args, **kwargs)
        self._request: request.Request | None = context_request
        self._user = getattr(self._request, "user", None)

    def validate_config(
        self,
        config: configs.S3FileTypeConfig,
    ) -> configs.S3FileTypeConfig:
        """Check that user can use dest."""
        if config.auth and not config.auth(self._user):
            raise exceptions.ValidationError(
                "Current user can't use this destination",
            )
        return config

    def validate(self, attrs: dict[str, typing.Any]) -> dict[str, typing.Any]:
        """Perform validations.

        Check what input data is valid for specified configuration.

        """
        errors: dict[str, str] = {}
        config: configs.S3FileTypeConfig = attrs["config"]
        filename: str = attrs["filename"]
        content_type: str = attrs["content_type"]
        content_length: int = attrs["content_length"]
        if config.allowed and content_type not in config.allowed:
            expected = ", ".join(config.allowed)
            errors["content_type"] = (
                f"Invalid file type - `{content_type}` of `{filename}`. "
                f"Expected: {expected}."
            )
        if config.content_length_range:
            min_bound, max_bound = config.content_length_range
            if min_bound > content_length:
                errors["content_length"] = (
                    "Invalid file size "
                    f"- {humanize.naturalsize(content_length)} "
                    f"of {filename}. "
                    f"Need between {humanize.naturalsize(min_bound)} "
                    f"and {humanize.naturalsize(max_bound)}."
                )
            if max_bound < content_length:
                errors["content_length"] = (
                    "Invalid file size "
                    f"- {humanize.naturalsize(content_length)} "
                    f"of {filename}. "
                    f"Need between {humanize.naturalsize(min_bound)} "
                    f"and {humanize.naturalsize(max_bound)}."
                )
        if errors:
            raise exceptions.ValidationError(errors)
        return attrs

__init__(context_request=None, *args, **kwargs)

Set current user.

Source code in saritasa_s3_tools/django/serializers.py
42
43
44
45
46
47
48
49
50
51
def __init__(
    self,
    context_request: request.Request | None = None,
    *args,  # noqa: ANN002
    **kwargs,
) -> None:
    """Set current user."""
    super().__init__(*args, **kwargs)
    self._request: request.Request | None = context_request
    self._user = getattr(self._request, "user", None)

validate(attrs)

Perform validations.

Check what input data is valid for specified configuration.

Source code in saritasa_s3_tools/django/serializers.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def validate(self, attrs: dict[str, typing.Any]) -> dict[str, typing.Any]:
    """Perform validations.

    Check what input data is valid for specified configuration.

    """
    errors: dict[str, str] = {}
    config: configs.S3FileTypeConfig = attrs["config"]
    filename: str = attrs["filename"]
    content_type: str = attrs["content_type"]
    content_length: int = attrs["content_length"]
    if config.allowed and content_type not in config.allowed:
        expected = ", ".join(config.allowed)
        errors["content_type"] = (
            f"Invalid file type - `{content_type}` of `{filename}`. "
            f"Expected: {expected}."
        )
    if config.content_length_range:
        min_bound, max_bound = config.content_length_range
        if min_bound > content_length:
            errors["content_length"] = (
                "Invalid file size "
                f"- {humanize.naturalsize(content_length)} "
                f"of {filename}. "
                f"Need between {humanize.naturalsize(min_bound)} "
                f"and {humanize.naturalsize(max_bound)}."
            )
        if max_bound < content_length:
            errors["content_length"] = (
                "Invalid file size "
                f"- {humanize.naturalsize(content_length)} "
                f"of {filename}. "
                f"Need between {humanize.naturalsize(min_bound)} "
                f"and {humanize.naturalsize(max_bound)}."
            )
    if errors:
        raise exceptions.ValidationError(errors)
    return attrs

validate_config(config)

Check that user can use dest.

Source code in saritasa_s3_tools/django/serializers.py
53
54
55
56
57
58
59
60
61
62
def validate_config(
    self,
    config: configs.S3FileTypeConfig,
) -> configs.S3FileTypeConfig:
    """Check that user can use dest."""
    if config.auth and not config.auth(self._user):
        raise exceptions.ValidationError(
            "Current user can't use this destination",
        )
    return config

S3UploadSerializer

Bases: Serializer

Serializer auto swagger documentation.

This serializer used just for packages that capable to generate openapi/swagger specs, so that front-end team could see specs for response for view.

Source code in saritasa_s3_tools/django/serializers.py
122
123
124
125
126
127
128
129
130
131
132
class S3UploadSerializer(serializers.Serializer):
    """Serializer auto swagger documentation.

    This serializer used just for packages that capable to generate
    openapi/swagger specs, so that front-end team
    could see specs for response for view.

    """

    url = serializers.URLField()
    params = S3ParamsSerializer()