Compare commits

...

11 Commits

Author SHA1 Message Date
Cristi Vîjdea 6b2ce7d0f9 Update changelog and release 1.8.0 2018-05-31 00:24:48 +03:00
Cristi Vîjdea 256a052564 Add ability to set Schema fields through the serializer Meta class (#134)
* Add swagger_schema_fields attribute to serializer Meta class
* Add documentation

Closes #132.
2018-05-31 00:15:21 +03:00
Cristi Vîjdea cc90bc1544 Add some coverage exemptions 2018-05-30 22:33:36 +03:00
Terence Honles ecee6f8177 apply fix from #58 to _SpecRenderer (#130)
* apply fix from #58 to _SpecRenderer
* Use JSONRenderer instead of HTML
2018-05-30 22:03:00 +03:00
werwty 408b31fc4f Avoid marking read_only fields as required (#133)
* Avoid marking read_only fields as required

Read only properties cannot be marked as required by a schema.
2018-05-30 21:56:52 +03:00
Cristi Vîjdea a4a11ad1ab Prevent crash when ViewInspector.get_operation returns None 2018-05-14 22:10:13 +03:00
Cristi Vîjdea aca0c4713e Allow body on HTTP DELETE view methods (#122)
* Allow body in delete requests
* Do not add request body to DELETE by default
* Check manual form parameters against body_methods
* Add tests
* Add changelog

Closes #118
2018-05-14 19:15:14 +03:00
Cristi Vîjdea 3077195396 Update swagger-ui to 3.14.2 and ReDoc to 2.0.0-alpha.20 2018-05-14 18:59:59 +03:00
Cristi Vîjdea 94f6ca8c89 Ignore python tests in node_modules 2018-05-14 18:57:29 +03:00
Cristi Vîjdea ae5eeeb600 Ignore None return from get_operation 2018-05-14 18:36:44 +03:00
Cristi Vîjdea 23ebe2ff3e Guard against views that throw exceptions from __init__ 2018-05-12 18:14:33 +03:00
19 changed files with 413 additions and 1801 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ You want to contribute some code? Great! Here are a few steps to get you started
$ virtualenv venv $ virtualenv venv
$ source venv/bin/activate $ source venv/bin/activate
(venv) $ pip install -e .[validation] (venv) $ pip install -e .[validation]
(venv) $ pip install -rrequirements/dev.txt "Django>=1.11.7" (venv) $ pip install -r requirements/dev.txt
#. **Make your changes and check them against the test project** #. **Make your changes and check them against the test project**
+31 -1
View File
@@ -3,6 +3,37 @@ Changelog
######### #########
*********
**1.8.0**
*********
*Release date: Jun 01, 2018*
- **ADDED:** added a :ref:`swagger_schema_fields <swagger_schema_fields>` field on serializer ``Meta`` classes for
customizing schema generation (:issue:`132`, :pr:`134`)
- **FIXED:** error responses from schema views are now rendered with ``JSONRenderer`` instead of throwing
confusing errors (:pr:`130`, :issue:`58`)
- **FIXED:** ``readOnly`` schema fields will now no longer be marked as ``required`` (:pr:`133`)
*********
**1.7.4**
*********
*Release date: May 14, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.14.2
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.20
- **FIXED:** ignore ``None`` return from ``get_operation`` to avoid empty ``Path`` objects in output
- **FIXED:** request body is now allowed on ``DELETE`` endpoints (:issue:`118`)
*********
**1.7.3**
*********
*Release date: May 12, 2018*
- **FIXED:** views whose ``__init__`` methods throw exceptions will now be ignored during endpoint enumeration
********* *********
**1.7.2** **1.7.2**
********* *********
@@ -12,7 +43,6 @@ Changelog
- **FIXED:** fixed generation of default ``SECURITY_REQUIREMENTS`` to match documented behaviour - **FIXED:** fixed generation of default ``SECURITY_REQUIREMENTS`` to match documented behaviour
- **FIXED:** ordering of ``SECURITY_REQUIREMENTS`` and ``SECURITY_DEFINITIONS`` is now stable - **FIXED:** ordering of ``SECURITY_REQUIREMENTS`` and ``SECURITY_DEFINITIONS`` is now stable
********* *********
**1.7.1** **1.7.1**
********* *********
+7 -1
View File
@@ -169,13 +169,19 @@ You can define some per-serializer options by adding a ``Meta`` class to your se
class Meta: class Meta:
... options here ... ... options here ...
Currently, the only option you can add here is .. _swagger_schema_fields:
The available options are:
* ``ref_name`` - a string which will be used as the model definition name for this serializer class; setting it to * ``ref_name`` - a string which will be used as the model definition name for this serializer class; setting it to
``None`` will force the serializer to be generated as an inline model everywhere it is used. If two serializers ``None`` will force the serializer to be generated as an inline model everywhere it is used. If two serializers
have the same ``ref_name``, both their usages will be replaced with a reference to the same definition. have the same ``ref_name``, both their usages will be replaced with a reference to the same definition.
If this option is not specified, all serializers have an implicit name derived from their class name, minus any If this option is not specified, all serializers have an implicit name derived from their class name, minus any
``Serializer`` suffix (e.g. ``UserSerializer`` -> ``User``, ``SerializerWithSuffix`` -> ``SerializerWithSuffix``) ``Serializer`` suffix (e.g. ``UserSerializer`` -> ``User``, ``SerializerWithSuffix`` -> ``SerializerWithSuffix``)
* ``swagger_schema_fields`` - a dictionary mapping :class:`.Schema` field names to values. These attributes
will be set on the :class:`.Schema` object generated from the ``Serializer``. Field names must be python values,
which are converted to Swagger ``Schema`` attribute names according to :func:`.make_swagger_name`.
Attribute names and values must conform to the `OpenAPI 2.0 specification <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject>`_.
************************* *************************
+121 -1610
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,8 +1,8 @@
{ {
"name": "drf-yasg", "name": "drf-yasg",
"dependencies": { "dependencies": {
"redoc": "^2.0.0-alpha.17", "redoc": "^2.0.0-alpha.20",
"swagger-ui-dist": "^3.14.1" "swagger-ui-dist": "^3.14.2"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
+17 -9
View File
@@ -86,14 +86,17 @@ class EndpointEnumerator(_EndpointEnumerator):
for pattern in patterns: for pattern in patterns:
path_regex = prefix + get_original_route(pattern) path_regex = prefix + get_original_route(pattern)
if isinstance(pattern, URLPattern): if isinstance(pattern, URLPattern):
path = self.get_path_from_regex(path_regex) try:
callback = pattern.callback path = self.get_path_from_regex(path_regex)
url_name = pattern.name callback = pattern.callback
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name): url_name = pattern.name
path = self.replace_version(path, callback) if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
for method in self.get_allowed_methods(callback): path = self.replace_version(path, callback)
endpoint = (path, method, callback) for method in self.get_allowed_methods(callback):
api_endpoints.append(endpoint) endpoint = (path, method, callback)
api_endpoints.append(endpoint)
except Exception: # pragma: no cover
logger.warning('failed to enumerate view', exc_info=True)
elif isinstance(pattern, URLResolver): elif isinstance(pattern, URLResolver):
nested_endpoints = self.get_api_endpoints( nested_endpoints = self.get_api_endpoints(
@@ -321,7 +324,9 @@ class OpenAPISchemaGenerator(object):
if not public and not self._gen.has_view_permissions(path, method, view): if not public and not self._gen.has_view_permissions(path, method, view):
continue continue
operations[method.lower()] = self.get_operation(view, path, prefix, method, components, request) operation = self.get_operation(view, path, prefix, method, components, request)
if operation is not None:
operations[method.lower()] = operation
if operations: if operations:
# since the common prefix is used as the API basePath, it must be stripped # since the common prefix is used as the API basePath, it must be stripped
@@ -362,6 +367,9 @@ class OpenAPISchemaGenerator(object):
view_inspector = view_inspector_cls(view, path, method, components, request, overrides) view_inspector = view_inspector_cls(view, path, method, components, request, overrides)
operation = view_inspector.get_operation(operation_keys) operation = view_inspector.get_operation(operation_keys)
if operation is None:
return None
if 'consumes' in operation and set(operation.consumes) == set(self.consumes): if 'consumes' in operation and set(operation.consumes) == set(self.consumes):
del operation.consumes del operation.consumes
if 'produces' in operation and set(operation.produces) == set(self.produces): if 'produces' in operation and set(operation.produces) == set(self.produces):
+4 -1
View File
@@ -276,7 +276,10 @@ class SerializerInspector(FieldInspector):
class ViewInspector(BaseInspector): class ViewInspector(BaseInspector):
body_methods = ('PUT', 'PATCH', 'POST') #: methods that are allowed to have a request body body_methods = ('PUT', 'PATCH', 'POST', 'DELETE') #: methods that are allowed to have a request body
#: methods that are assumed to require a request body determined by the view's ``serializer_class``
implicit_body_methods = ('PUT', 'PATCH', 'POST')
# real values set in __init__ to prevent import errors # real values set in __init__ to prevent import errors
field_inspectors = [] #: field_inspectors = [] #:
+40 -6
View File
@@ -22,12 +22,39 @@ class InlineSerializerInspector(SerializerInspector):
#: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section #: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section
use_definitions = False use_definitions = False
def add_manual_fields(self, serializer, schema):
"""Set fields from the ``swagger_schem_fields`` attribute on the serializer's Meta class. This method is called
only for serializers that are converted into ``openapi.Schema`` objects.
:param serializer: serializer instance
:param openapi.Schema schema: the schema object to be modified in-place
"""
serializer_meta = getattr(serializer, 'Meta', None)
swagger_schema_fields = getattr(serializer_meta, 'swagger_schema_fields', {})
if swagger_schema_fields:
for attr, val in swagger_schema_fields.items():
setattr(schema, attr, val)
def get_schema(self, serializer): def get_schema(self, serializer):
return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions) result = self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions)
schema = openapi.resolve_ref(result, self.components)
self.add_manual_fields(serializer, schema)
return result
def add_manual_parameters(self, serializer, parameters):
"""Add/replace parameters from the given list of automatically generated request parameters. This method
is called only when the serializer is converted into a list of parameters for use in a form data request.
:param serializer: serializer instance
:param list[openapi.Parameter] parameters: genereated parameters
:return: modified parameters
:rtype: list[openapi.Parameter]
"""
return parameters
def get_request_parameters(self, serializer, in_): def get_request_parameters(self, serializer, in_):
fields = getattr(serializer, 'fields', {}) fields = getattr(serializer, 'fields', {})
return [ parameters = [
self.probe_field_inspectors( self.probe_field_inspectors(
value, openapi.Parameter, self.use_definitions, value, openapi.Parameter, self.use_definitions,
name=self.get_parameter_name(key), in_=in_ name=self.get_parameter_name(key), in_=in_
@@ -36,12 +63,17 @@ class InlineSerializerInspector(SerializerInspector):
in fields.items() in fields.items()
] ]
return self.add_manual_parameters(serializer, parameters)
def get_property_name(self, field_name): def get_property_name(self, field_name):
return field_name return field_name
def get_parameter_name(self, field_name): def get_parameter_name(self, field_name):
return field_name return field_name
def get_serializer_ref_name(self, serializer):
return get_serializer_ref_name(serializer)
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs): def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs) SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
@@ -55,7 +87,7 @@ class InlineSerializerInspector(SerializerInspector):
if swagger_object_type != openapi.Schema: if swagger_object_type != openapi.Schema:
raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__) raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__)
ref_name = get_serializer_ref_name(field) ref_name = self.get_serializer_ref_name(field)
def make_schema_definition(): def make_schema_definition():
properties = OrderedDict() properties = OrderedDict()
@@ -67,10 +99,12 @@ class InlineSerializerInspector(SerializerInspector):
} }
prop_kwargs = filter_none(prop_kwargs) prop_kwargs = filter_none(prop_kwargs)
properties[property_name] = self.probe_field_inspectors( child_schema = self.probe_field_inspectors(
child, ChildSwaggerType, use_references, **prop_kwargs child, ChildSwaggerType, use_references, **prop_kwargs
) )
if child.required: properties[property_name] = child_schema
if child.required and not getattr(child_schema, 'read_only', False):
required.append(property_name) required.append(property_name)
result = SwaggerType( result = SwaggerType(
@@ -527,7 +561,7 @@ else:
try: try:
from rest_framework_recursive.fields import RecursiveField from rest_framework_recursive.fields import RecursiveField
except ImportError: except ImportError: # pragma: no cover
class RecursiveFieldInspector(FieldInspector): class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)""" """Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
pass pass
+5 -2
View File
@@ -101,7 +101,7 @@ class SwaggerAutoSchema(ViewInspector):
if isinstance(body_override, openapi.Schema.OR_REF): if isinstance(body_override, openapi.Schema.OR_REF):
return body_override return body_override
return force_serializer_instance(body_override) return force_serializer_instance(body_override)
elif self.method in self.body_methods: elif self.method in self.implicit_body_methods:
return self.get_view_serializer() return self.get_view_serializer()
return None return None
@@ -144,8 +144,11 @@ class SwaggerAutoSchema(ViewInspector):
raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body") raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body")
if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover
if any(param.in_ == openapi.IN_BODY for param in parameters.values()): if any(param.in_ == openapi.IN_BODY for param in parameters.values()):
raise SwaggerGenerationError("cannot add form parameters when the request has a request schema; " raise SwaggerGenerationError("cannot add form parameters when the request has a request body; "
"did you forget to set an appropriate parser class on the view?") "did you forget to set an appropriate parser class on the view?")
if self.method not in self.body_methods:
raise SwaggerGenerationError("form parameters can only be applied to (" + ','.join(self.body_methods) +
") HTTP methods")
parameters.update(param_list_to_odict(manual_parameters)) parameters.update(param_list_to_odict(manual_parameters))
return list(parameters.values()) return list(parameters.values())
+9 -3
View File
@@ -1,5 +1,5 @@
from django.shortcuts import render, resolve_url from django.shortcuts import render, resolve_url
from rest_framework.renderers import BaseRenderer, TemplateHTMLRenderer from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer
from rest_framework.utils import json from rest_framework.utils import json
from drf_yasg.openapi import Swagger from drf_yasg.openapi import Swagger
@@ -10,7 +10,7 @@ from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
class _SpecRenderer(BaseRenderer): class _SpecRenderer(BaseRenderer):
"""Base class for text renderers. Handles encoding and validation.""" """Base class for text renderers. Handles encoding and validation."""
charset = None charset = 'utf-8'
validators = [] validators = []
codec_class = None codec_class = None
@@ -22,6 +22,12 @@ class _SpecRenderer(BaseRenderer):
def render(self, data, media_type=None, renderer_context=None): def render(self, data, media_type=None, renderer_context=None):
assert self.codec_class, "must override codec_class" assert self.codec_class, "must override codec_class"
codec = self.codec_class(self.validators) codec = self.codec_class(self.validators)
if not isinstance(data, Swagger): # pragma: no cover
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58
return JSONRenderer().render(data, media_type, renderer_context)
return codec.encode(data) return codec.encode(data)
@@ -53,7 +59,7 @@ class _UIRenderer(BaseRenderer):
template = '' template = ''
def render(self, swagger, accepted_media_type=None, renderer_context=None): def render(self, swagger, accepted_media_type=None, renderer_context=None):
if not isinstance(swagger, Swagger): if not isinstance(swagger, Swagger): # pragma: no cover
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response`` # if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it # in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58 # see https://github.com/axnsan12/drf-yasg/issues/58
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -11,7 +11,7 @@ class ArticleSerializer(serializers.ModelSerializer):
read_only=True, read_only=True,
) )
uuid = serializers.UUIDField(help_text="should articles have UUIDs?", read_only=True) uuid = serializers.UUIDField(help_text="should articles have UUIDs?", read_only=True)
cover_name = serializers.FileField(use_url=False, source='cover', read_only=True) cover_name = serializers.FileField(use_url=False, source='cover', required=True)
group = serializers.SlugRelatedField(slug_field='uuid', queryset=ArticleGroup.objects.all()) group = serializers.SlugRelatedField(slug_field='uuid', queryset=ArticleGroup.objects.all())
original_group = serializers.SlugRelatedField(slug_field='uuid', read_only=True) original_group = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
+35 -12
View File
@@ -33,6 +33,21 @@ class SnippetList(generics.ListCreateAPIView):
"""post method docstring""" """post method docstring"""
return super(SnippetList, self).post(request, *args, **kwargs) return super(SnippetList, self).post(request, *args, **kwargs)
@swagger_auto_schema(
operation_id='snippets_delete_bulk',
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'body': openapi.Schema(
type=openapi.TYPE_STRING,
description='this should not crash (request body on DELETE method)'
)
}
),
)
def delete(self, *args, **kwargs):
pass
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
""" """
@@ -56,18 +71,26 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
"""patch method docstring""" """patch method docstring"""
return super(SnippetDetail, self).patch(request, *args, **kwargs) return super(SnippetDetail, self).patch(request, *args, **kwargs)
@swagger_auto_schema(manual_parameters=[ @swagger_auto_schema(
openapi.Parameter( manual_parameters=[
name='id', in_=openapi.IN_PATH, openapi.Parameter(
type=openapi.TYPE_INTEGER, name='id', in_=openapi.IN_PATH,
description="path parameter override", type=openapi.TYPE_INTEGER,
required=True description="path parameter override",
), required=True
], responses={ ),
status.HTTP_204_NO_CONTENT: openapi.Response( openapi.Parameter(
description="This should not crash" name='delete_form_param', in_=openapi.IN_FORM,
) type=openapi.TYPE_INTEGER,
}) description="this should not crash (form parameter on DELETE method)"
),
],
responses={
status.HTTP_204_NO_CONTENT: openapi.Response(
description="this should not crash (response object with no schema)"
)
}
)
def delete(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs):
"""delete method docstring""" """delete method docstring"""
return super(SnippetDetail, self).patch(request, *args, **kwargs) return super(SnippetDetail, self).patch(request, *args, **kwargs)
+11
View File
@@ -1,3 +1,5 @@
from collections import OrderedDict
from django.utils import timezone from django.utils import timezone
from rest_framework import serializers from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField from rest_framework_recursive.fields import RecursiveField
@@ -26,6 +28,15 @@ class TodoYetAnotherSerializer(serializers.ModelSerializer):
model = TodoYetAnother model = TodoYetAnother
fields = ('title', 'todo') fields = ('title', 'todo')
depth = 2 depth = 2
swagger_schema_fields = {
'example': OrderedDict([
('title', 'parent'),
('todo', OrderedDict([
('title', 'child'),
('todo', None),
])),
])
}
class TodoTreeSerializer(serializers.ModelSerializer): class TodoTreeSerializer(serializers.ModelSerializer):
+28 -1
View File
@@ -388,6 +388,24 @@ paths:
$ref: '#/definitions/Snippet' $ref: '#/definitions/Snippet'
tags: tags:
- snippets - snippets
delete:
operationId: snippetsDeleteBulk
description: SnippetList classdoc
parameters:
- name: data
in: body
required: true
schema:
type: object
properties:
body:
description: this should not crash (request body on DELETE method)
type: string
responses:
'204':
description: ''
tags:
- snippets
parameters: [] parameters: []
/snippets/{id}/: /snippets/{id}/:
get: get:
@@ -442,9 +460,13 @@ paths:
description: path parameter override description: path parameter override
required: true required: true
type: integer type: integer
- name: delete_form_param
in: formData
description: this should not crash (form parameter on DELETE method)
type: integer
responses: responses:
'204': '204':
description: This should not crash description: this should not crash (response object with no schema)
tags: tags:
- snippets - snippets
parameters: parameters:
@@ -1556,6 +1578,11 @@ definitions:
minLength: 1 minLength: 1
readOnly: true readOnly: true
readOnly: true readOnly: true
example:
title: parent
todo:
title: child
todo: null
UserSerializerrr: UserSerializerrr:
required: required:
- username - username
+1 -1
View File
@@ -46,7 +46,7 @@ commands =
[pytest] [pytest]
DJANGO_SETTINGS_MODULE = testproj.settings.local DJANGO_SETTINGS_MODULE = testproj.settings.local
python_paths = testproj python_paths = testproj
addopts = -n 3 addopts = -n 3 --ignore=node_modules
[flake8] [flake8]
max-line-length = 120 max-line-length = 120