Skip to content

Commit

Permalink
Merge pull request #583 from johnthagen/patch-2
Browse files Browse the repository at this point in the history
Add blueprint for drf-extra-fields Base64FileField
  • Loading branch information
tfranzel authored Oct 28, 2021
2 parents 31e7698 + 6c4c2f1 commit 56d720d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/blueprints.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,19 @@ Framework ones adding separated serializers for read and write operations.
__ https://github.com/vintasoftware/drf-rw-serializers

.. literalinclude:: blueprints/drf_rw_serializers.py

drf-extra-fields Base64FileField
--------------------------------

`drf-extra-fields`__ provides a ``Base64FileField`` and ``Base64ImageField`` that automatically
represent binary files as base64 encoded strings. This is a useful way to embed files within a
larger JSON API and keep all data within the same tree and served with a single request or
response.

Because requests to these fields require a base64 encoded string and responses can be either a
URI or base64 contents (if ``represent_as_base64=True``) custom schema generation
logic is required as this differs from the default DRF ``FileField``.

.. literalinclude:: blueprints/drf_extra_fields.py

__ https://github.com/Hipo/drf-extra-fields
20 changes: 20 additions & 0 deletions docs/blueprints/drf_extra_fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
from drf_spectacular.plumbing import build_basic_type
from drf_spectacular.types import OpenApiTypes


class Base64FileFieldSchema(OpenApiSerializerFieldExtension):
target_class = "drf_extra_fields.fields.Base64FileField"

def map_serializer_field(self, auto_schema, direction):
if direction == "request":
return build_basic_type(OpenApiTypes.BYTE)
elif direction == "response":
if self.target.represent_in_base64:
return build_basic_type(OpenApiTypes.BYTE)
else:
return build_basic_type(OpenApiTypes.URI)


class Base64ImageFieldSchema(Base64FileFieldSchema):
target_class = "drf_extra_fields.fields.Base64ImageField"

0 comments on commit 56d720d

Please sign in to comment.