Skip to content

Commit

Permalink
Handling read_only/write_only fields on OpenAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
fao89 committed Nov 4, 2019
1 parent 2203fee commit 31a945a
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGES/5622.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Handling `read_only` and `write_only` fields on OpenAPISchema.
70 changes: 69 additions & 1 deletion pulpcore/app/openapigenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,42 @@
from drf_yasg.generators import OpenAPISchemaGenerator
from drf_yasg.inspectors import SwaggerAutoSchema
from drf_yasg.openapi import Parameter
from drf_yasg.utils import filter_none, force_real_str
from drf_yasg.utils import filter_none, force_real_str, no_body


class ReadOnly:
"""
Read only objects from schema.
Patch: https://github.com/axnsan12/drf-yasg/issues/70#issuecomment-485050813
"""

def __init__(self, serializer):
"""
Get the read_only fields.
"""

new_fields = OrderedDict()
for field_name, field in serializer.get_fields().items():
if not field.write_only:
new_fields[field_name] = field
serializer.fields = new_fields


class WriteOnly:
"""
Write only objects from schema.
Patch: https://github.com/axnsan12/drf-yasg/issues/70#issuecomment-485050813
"""

def __init__(self, serializer):
"""
Get the write_only fields.
"""
new_fields = OrderedDict()
for field_name, field in serializer.get_fields().items():
if not field.read_only:
new_fields[field_name] = field
serializer.fields = new_fields


class Paths(openapi.SwaggerDict):
Expand Down Expand Up @@ -373,3 +408,36 @@ def get_tags(self, operation_keys):
tags = [' '.join(operation_keys[:-1])]

return tags

def get_view_serializer(self):
"""
Return the view's serializer without read_only fields.
Patch: https://github.com/axnsan12/drf-yasg/issues/70#issuecomment-485050813
"""

return self._convert_serializer(WriteOnly)

def get_default_response_serializer(self):
"""
Return the default response serializer for this endpoint without write_only fields.
Patch: https://github.com/axnsan12/drf-yasg/issues/70#issuecomment-485050813
"""

body_override = self._get_request_body_override()
if body_override and body_override is not no_body:
return body_override

return self._convert_serializer(ReadOnly)

def _convert_serializer(self, new_class):
"""
Creates a new serializer without read_only/write_only fields.
Patch: https://github.com/axnsan12/drf-yasg/issues/70#issuecomment-485050813
"""

serializer = super().get_view_serializer()
if not serializer:
return serializer

new_class(serializer)
return serializer

0 comments on commit 31a945a

Please sign in to comment.