From e199a8d8b35a5dc5748e0acaceb05ac03e837c60 Mon Sep 17 00:00:00 2001 From: Sonny Bakker Date: Tue, 20 Sep 2022 15:03:43 +0200 Subject: [PATCH] [#210] add FileFieldExtension Based on https://drf-spectacular.readthedocs.io/en/latest/blueprints.html#drf-extra-fields-base64filefield --- vng_api_common/inspectors/__init__.py | 1 + vng_api_common/inspectors/files.py | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 vng_api_common/inspectors/files.py diff --git a/vng_api_common/inspectors/__init__.py b/vng_api_common/inspectors/__init__.py index 19cbb793..364e5255 100644 --- a/vng_api_common/inspectors/__init__.py +++ b/vng_api_common/inspectors/__init__.py @@ -4,6 +4,7 @@ HyperlinkedRelatedFieldExtension, ReadOnlyFieldExtension, ) +from .files import FileFieldExtension from .geojson import GeometryFieldExtension from .polymorphic import PolymorphicSerializerExtension from .query import FilterExtension diff --git a/vng_api_common/inspectors/files.py b/vng_api_common/inspectors/files.py new file mode 100644 index 00000000..a66b7270 --- /dev/null +++ b/vng_api_common/inspectors/files.py @@ -0,0 +1,26 @@ +from django.utils.translation import gettext as _ + +from drf_spectacular.extensions import OpenApiSerializerFieldExtension +from drf_spectacular.plumbing import build_basic_type +from drf_spectacular.types import OpenApiTypes + + +class FileFieldExtension(OpenApiSerializerFieldExtension): + target_class = "drf_extra_fields.fields.Base64FileField" + match_subclasses = True + + def map_serializer_field(self, auto_schema, direction): + base64_schema = { + **build_basic_type(OpenApiTypes.BYTE), + "description": _("Base64 encoded binary content."), + } + + uri_schema = { + **build_basic_type(OpenApiTypes.URI), + "description": _("Download URL of the binary content."), + } + + if direction == "request": + return base64_schema + elif direction == "response": + return uri_schema if not self.target.represent_in_base64 else base64_schema