Skip to content

Commit

Permalink
Fixed drf JSONField being interpreted as Any
Browse files Browse the repository at this point in the history
Drf JSONField is actually 'any' because it can be of any type (list, obj
int, bool, etc). Nevertheless, we (and drf-spectacular) always interpret
it as being of type 'object'.

In v0.27.0, drf-spectacular fixed that on their side, which broke us.

Although it is not correct to keep using JSONFields strictly as a object,
this commit adds a drf-spectacular extension that enforces that it should
always be trated as an 'object' on openapi schema generation.

The reason is to provide a safe fix for our users, who need their
bindings working the same way as they always did.

Closes: pulp#3639
  • Loading branch information
pedro-psb committed Jul 1, 2024
1 parent bb025a6 commit 74f6803
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGES/3639.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed openapi schema generation by monkeypatching that drf JSONField is always an OA 'object'.
6 changes: 6 additions & 0 deletions pulp_rpm/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@ class PulpRpmPluginAppConfig(PulpPluginAppConfig):
version = "3.28.0.dev"
python_package_name = "pulp-rpm"
domain_compatible = True

def ready(self):
# include drf-spectacular Extension module
import pulp_rpm.app.schema.extensions # noqa: E402, F401

super().ready()
24 changes: 24 additions & 0 deletions pulp_rpm/app/schema/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""drf-spectacular Extensions.
See:
https://drf-spectacular.readthedocs.io/en/latest/customization.html#step-5-extensions
"""

from drf_spectacular.extensions import OpenApiSerializerFieldExtension
from drf_spectacular.plumbing import build_basic_type
from drf_spectacular.types import OpenApiTypes


class RestrictedJsonFieldExtension(OpenApiSerializerFieldExtension):
"""
Workaround to makes drf JSONField to produce only Object Type.
See:
https://github.com/tfranzel/drf-spectacular/issues/1242
"""

target_class = "rest_framework.fields.JSONField"
# match_subclasses = True # not needed here but good to know.

def map_serializer_field(self, auto_schema, direction):
return build_basic_type(OpenApiTypes.OBJECT)

0 comments on commit 74f6803

Please sign in to comment.