Move AutoSchema serializer instantiation to common method

This commit is contained in:
Reupen Shah 2019-07-30 20:42:23 +01:00 committed by Carlton Gibson
parent 7e1c4be7ce
commit a3f244d85e

View File

@ -419,23 +419,26 @@ class AutoSchema(ViewInspector):
schema['maximum'] = int(digits * '9') + 1 schema['maximum'] = int(digits * '9') + 1
schema['minimum'] = -schema['maximum'] schema['minimum'] = -schema['maximum']
def _get_request_body(self, path, method): def _get_serializer(self, method, path):
view = self.view view = self.view
if method not in ('PUT', 'PATCH', 'POST'):
return {}
if not hasattr(view, 'get_serializer'): if not hasattr(view, 'get_serializer'):
return {} return None
try: try:
serializer = view.get_serializer() return view.get_serializer()
except exceptions.APIException: except exceptions.APIException:
serializer = None
warnings.warn('{}.get_serializer() raised an exception during ' warnings.warn('{}.get_serializer() raised an exception during '
'schema generation. Serializer fields will not be ' 'schema generation. Serializer fields will not be '
'generated for {} {}.' 'generated for {} {}.'
.format(view.__class__.__name__, method, path)) .format(view.__class__.__name__, method, path))
return None
def _get_request_body(self, path, method):
if method not in ('PUT', 'PATCH', 'POST'):
return {}
serializer = self._get_serializer(path, method)
if not isinstance(serializer, serializers.Serializer): if not isinstance(serializer, serializers.Serializer):
return {} return {}
@ -459,24 +462,15 @@ class AutoSchema(ViewInspector):
def _get_responses(self, path, method): def _get_responses(self, path, method):
# TODO: Handle multiple codes. # TODO: Handle multiple codes.
content = {} content = {}
view = self.view serializer = self._get_serializer(path, method)
if hasattr(view, 'get_serializer'):
try:
serializer = view.get_serializer()
except exceptions.APIException:
serializer = None
warnings.warn('{}.get_serializer() raised an exception during '
'schema generation. Serializer fields will not be '
'generated for {} {}.'
.format(view.__class__.__name__, method, path))
if isinstance(serializer, serializers.Serializer): if isinstance(serializer, serializers.Serializer):
content = self._map_serializer(serializer) content = self._map_serializer(serializer)
# No write_only fields for response. # No write_only fields for response.
for name, schema in content['properties'].copy().items(): for name, schema in content['properties'].copy().items():
if 'writeOnly' in schema: if 'writeOnly' in schema:
del content['properties'][name] del content['properties'][name]
content['required'] = [f for f in content['required'] if f != name] content['required'] = [f for f in content['required'] if f != name]
return { return {
'200': { '200': {