Compare commits

...

8 Commits

Author SHA1 Message Date
Cristi Vîjdea 7065429d47 Remove python 2.7 + DRF 3.8 build from Travis CI jobs 2018-05-05 15:53:40 +03:00
Cristi Vîjdea bd727fbe88 Update swagger-ui to 3.14.1
Add settings key for ``showCommonExtensions``
2018-05-05 15:33:38 +03:00
Cristi Vîjdea 698a175a1b Remove python_requires from Django requirement
Fixes #113.
2018-05-02 20:30:09 +03:00
Fabian Weisshaar 5b225423ae Set min_length=1 when allow_blank=False (#112) 2018-04-27 13:02:26 +03:00
Cristi Vîjdea 209201b9a5 Make insertion order of SwaggerDict extra parameters consistent 2018-04-27 12:12:36 +03:00
Cristi Vîjdea ca00ed35be Install pytest-django from PyPI 2018-04-27 12:04:20 +03:00
Cristi Vîjdea 4e7fa28744 Superficial fixes 2018-04-27 01:53:05 +03:00
Roman Sichny 979ec84630 Django rest framework recursive support (#110)
* add get_serializer_ref_name utility function
* implement RecursiveFieldInspector
* add option to allow non-existing reference in SchemaRef
* add examples and README
* Update changelog and docs
2018-04-27 01:51:10 +03:00
28 changed files with 872 additions and 513 deletions
+3 -1
View File
@@ -2,7 +2,6 @@ language: python
cache: pip cache: pip
python: python:
- '2.7'
- '3.4' - '3.4'
- '3.5' - '3.5'
- '3.6' - '3.6'
@@ -14,6 +13,9 @@ env:
jobs: jobs:
include: include:
- stage: test - stage: test
python: '2.7'
env: DRF=3.7
-
python: '3.6' python: '3.6'
env: DRF=master env: DRF=master
- -
+6
View File
@@ -353,6 +353,12 @@ Integration with `djangorestframework-camel-case <https://github.com/vbabiy/djan
provided out of the box - if you have ``djangorestframework-camel-case`` installed and your ``APIView`` uses provided out of the box - if you have ``djangorestframework-camel-case`` installed and your ``APIView`` uses
``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer``, all property names will be converted to *camelCase* by default. ``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer``, all property names will be converted to *camelCase* by default.
djangorestframework-recursive
===============================
Integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_ is
provided out of the box - if you have ``djangorestframework-recursive`` installed.
.. |travis| image:: https://img.shields.io/travis/axnsan12/drf-yasg/master.svg .. |travis| image:: https://img.shields.io/travis/axnsan12/drf-yasg/master.svg
:target: https://travis-ci.org/axnsan12/drf-yasg :target: https://travis-ci.org/axnsan12/drf-yasg
:alt: Travis CI :alt: Travis CI
+24
View File
@@ -3,6 +3,30 @@ Changelog
######### #########
*********
**1.7.1**
*********
*Release date: May 05, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.14.1
- **IMPROVED:** set ``swagger-ui`` ``showCommonExtensions`` to ``True`` by default and add
``SHOW_COMMON_EXTENSIONS`` setting key
*********
**1.7.0**
*********
*Release date: Apr 27, 2018*
- **ADDED:** added integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_
(:issue:`109`, :pr:`110`, thanks to :ghuser:`rsichny`)
*NOTE:* in order for this to work, you will have to add the new ``drf_yasg.inspectors.RecursiveFieldInspector`` to
your ``DEFAULT_FIELD_INSPECTORS`` array if you changed it from the default value
- **FIXED:** ``SchemaRef`` now supports cyclical references via the ``ignore_unresolved`` argument
********* *********
**1.6.2** **1.6.2**
********* *********
+10
View File
@@ -67,6 +67,7 @@ to this list.
:class:`'drf_yasg.inspectors.FileFieldInspector' <.inspectors.FileFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.FileFieldInspector' <.inspectors.FileFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.DictFieldInspector' <.inspectors.DictFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.DictFieldInspector' <.inspectors.DictFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.HiddenFieldInspector' <.inspectors.HiddenFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.HiddenFieldInspector' <.inspectors.HiddenFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.RecursiveFieldInspector' <.inspectors.RecursiveFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \
``]`` ``]``
@@ -254,6 +255,15 @@ Controls how many levels are expaned by default when showing nested models.
**Default**: :python:`3` |br| **Default**: :python:`3` |br|
*Maps to parameter*: ``defaultModelExpandDepth`` *Maps to parameter*: ``defaultModelExpandDepth``
DEFAULT_MODEL_DEPTH
-------------------
Controls the display of extensions (``pattern``, ``maxLength``, ``minLength``, ``maximum``, ```minimum``) fields and
values for Parameters.
**Default**: :python:`True` |br|
*Maps to parameter*: ``showCommonExtensions``
.. _oauth2-settings: .. _oauth2-settings:
OAUTH2_REDIRECT_URL OAUTH2_REDIRECT_URL
+414 -414
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "drf-yasg", "name": "drf-yasg",
"dependencies": { "dependencies": {
"redoc": "^2.0.0-alpha.17", "redoc": "^2.0.0-alpha.17",
"swagger-ui-dist": "^3.13.6" "swagger-ui-dist": "^3.14.1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
+1 -2
View File
@@ -8,5 +8,4 @@ six>=1.10.0
uritemplate>=3.0.0 uritemplate>=3.0.0
djangorestframework>=3.7.7 djangorestframework>=3.7.7
Django>=1.11.7,<2.0; python_version <= "2.7" Django>=1.11.7
Django>=1.11.7; python_version >= "3.4"
+1 -2
View File
@@ -3,8 +3,7 @@ pytest>=2.9
pytest-pythonpath>=0.7.1 pytest-pythonpath>=0.7.1
pytest-cov>=2.5.1 pytest-cov>=2.5.1
pytest-xdist>=1.22.0 pytest-xdist>=1.22.0
# latest pip version of pytest-django is more than a year old and does not support Django 2.0 pytest-django>=3.2.0
git+https://github.com/pytest-dev/pytest-django.git@94cccb956435dd7a719606744ee7608397e1eafb
datadiff==2.0.0 datadiff==2.0.0
-r testproj.txt -r testproj.txt
+1
View File
@@ -5,5 +5,6 @@ django-cors-headers>=2.1.0
django-filter>=1.1.0,<2.0; python_version == "2.7" django-filter>=1.1.0,<2.0; python_version == "2.7"
django-filter>=1.1.0; python_version >= "3.4" django-filter>=1.1.0; python_version >= "3.4"
djangorestframework-camel-case>=0.2.0 djangorestframework-camel-case>=0.2.0
djangorestframework-recursive>=0.1.2
dj-database-url>=0.4.2 dj-database-url>=0.4.2
user_agents>=1.1.0 user_agents>=1.1.0
+3 -1
View File
@@ -6,12 +6,13 @@ SWAGGER_DEFAULTS = {
'DEFAULT_FIELD_INSPECTORS': [ 'DEFAULT_FIELD_INSPECTORS': [
'drf_yasg.inspectors.CamelCaseJSONFilter', 'drf_yasg.inspectors.CamelCaseJSONFilter',
'drf_yasg.inspectors.RecursiveFieldInspector',
'drf_yasg.inspectors.ReferencingSerializerInspector', 'drf_yasg.inspectors.ReferencingSerializerInspector',
'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.ChoiceFieldInspector', 'drf_yasg.inspectors.ChoiceFieldInspector',
'drf_yasg.inspectors.FileFieldInspector', 'drf_yasg.inspectors.FileFieldInspector',
'drf_yasg.inspectors.DictFieldInspector', 'drf_yasg.inspectors.DictFieldInspector',
'drf_yasg.inspectors.HiddenFieldInspector', 'drf_yasg.inspectors.HiddenFieldInspector',
'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.SimpleFieldInspector', 'drf_yasg.inspectors.SimpleFieldInspector',
'drf_yasg.inspectors.StringDefaultFieldInspector', 'drf_yasg.inspectors.StringDefaultFieldInspector',
], ],
@@ -44,6 +45,7 @@ SWAGGER_DEFAULTS = {
'SHOW_EXTENSIONS': True, 'SHOW_EXTENSIONS': True,
'DEFAULT_MODEL_RENDERING': 'model', 'DEFAULT_MODEL_RENDERING': 'model',
'DEFAULT_MODEL_DEPTH': 3, 'DEFAULT_MODEL_DEPTH': 3,
'SHOW_COMMON_EXTENSIONS': True,
'OAUTH2_REDIRECT_URL': None, 'OAUTH2_REDIRECT_URL': None,
'OAUTH2_CONFIG': {}, 'OAUTH2_CONFIG': {},
'SUPPORTED_SUBMIT_METHODS': [ 'SUPPORTED_SUBMIT_METHODS': [
-1
View File
@@ -401,7 +401,6 @@ class OpenAPISchemaGenerator(object):
""" """
parameters = [] parameters = []
queryset = getattr(view_cls, 'queryset', None) queryset = getattr(view_cls, 'queryset', None)
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
for variable in sorted(uritemplate.variables(path)): for variable in sorted(uritemplate.variables(path)):
model, model_field = get_queryset_field(queryset, variable) model, model_field = get_queryset_field(queryset, variable)
+5 -5
View File
@@ -4,8 +4,8 @@ from .base import (
) )
from .field import ( from .field import (
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector, CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector,
InlineSerializerInspector, ReferencingSerializerInspector, RelatedFieldInspector, SimpleFieldInspector, InlineSerializerInspector, RecursiveFieldInspector, ReferencingSerializerInspector, RelatedFieldInspector,
StringDefaultFieldInspector SimpleFieldInspector, StringDefaultFieldInspector
) )
from .query import CoreAPICompatInspector, DjangoRestResponsePagination from .query import CoreAPICompatInspector, DjangoRestResponsePagination
from .view import SwaggerAutoSchema from .view import SwaggerAutoSchema
@@ -23,9 +23,9 @@ __all__ = [
'CoreAPICompatInspector', 'DjangoRestResponsePagination', 'CoreAPICompatInspector', 'DjangoRestResponsePagination',
# field inspectors # field inspectors
'InlineSerializerInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector', 'SimpleFieldInspector', 'InlineSerializerInspector', 'RecursiveFieldInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector',
'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector', 'StringDefaultFieldInspector', 'SimpleFieldInspector', 'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector',
'CamelCaseJSONFilter', 'HiddenFieldInspector', 'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector',
# view inspectors # view inspectors
'SwaggerAutoSchema', 'SwaggerAutoSchema',
+28 -14
View File
@@ -10,7 +10,7 @@ from rest_framework.settings import api_settings as rest_framework_settings
from .. import openapi from .. import openapi
from ..errors import SwaggerGenerationError from ..errors import SwaggerGenerationError
from ..utils import decimal_as_float, filter_none from ..utils import decimal_as_float, filter_none, get_serializer_ref_name
from .base import FieldInspector, NotHandled, SerializerInspector from .base import FieldInspector, NotHandled, SerializerInspector
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -55,23 +55,12 @@ 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__)
serializer = field ref_name = get_serializer_ref_name(field)
serializer_meta = getattr(serializer, 'Meta', None)
serializer_name = type(serializer).__name__
if hasattr(serializer_meta, 'ref_name'):
ref_name = serializer_meta.ref_name
elif serializer_name == 'NestedSerializer' and isinstance(serializer, serializers.ModelSerializer):
logger.debug("Forcing inline output for ModelSerializer named 'NestedSerializer': " + str(serializer))
ref_name = None
else:
ref_name = serializer_name
if ref_name.endswith('Serializer'):
ref_name = ref_name[:-len('Serializer')]
def make_schema_definition(): def make_schema_definition():
properties = OrderedDict() properties = OrderedDict()
required = [] required = []
for property_name, child in serializer.fields.items(): for property_name, child in field.fields.items():
property_name = self.get_property_name(property_name) property_name = self.get_property_name(property_name)
prop_kwargs = { prop_kwargs = {
'read_only': child.read_only or None 'read_only': child.read_only or None
@@ -292,6 +281,10 @@ def find_limits(field):
if attr not in limits or improves(limit_value, limits[attr]): if attr not in limits or improves(limit_value, limits[attr]):
limits[attr] = limit_value limits[attr] = limit_value
if hasattr(field, "allow_blank") and not field.allow_blank:
if limits.get('min_length', 0) < 1:
limits['min_length'] = 1
return OrderedDict(sorted(limits.items())) return OrderedDict(sorted(limits.items()))
@@ -531,3 +524,24 @@ else:
return camelize_schema(result, self.components) return camelize_schema(result, self.components)
return result return result
try:
from rest_framework_recursive.fields import RecursiveField
except ImportError:
class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
pass
else:
class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema:
assert use_references is True, "Can not create schema for RecursiveField when use_references is False"
ref_name = get_serializer_ref_name(field.proxied)
assert ref_name is not None, "Can not create RecursiveField schema for inline ModelSerializer"
return openapi.SchemaRef(self.components.with_scope(openapi.SCHEMA_DEFINITIONS), ref_name,
ignore_unresolved=True)
return NotHandled
+11 -8
View File
@@ -116,7 +116,7 @@ class SwaggerDict(OrderedDict):
which would result in the extra attributes being added first. For this reason, we defer the insertion of the which would result in the extra attributes being added first. For this reason, we defer the insertion of the
attributes and require that subclasses call ._insert_extras__ at the end of their __init__ method. attributes and require that subclasses call ._insert_extras__ at the end of their __init__ method.
""" """
for attr, val in self._extras__.items(): for attr, val in sorted(self._extras__.items()):
setattr(self, attr, val) setattr(self, attr, val)
@staticmethod @staticmethod
@@ -437,7 +437,7 @@ class Schema(SwaggerDict):
super(Schema, self).__init__(**extra) super(Schema, self).__init__(**extra)
if required is True or required is False: if required is True or required is False:
# common error # common error
raise AssertionError("the `requires` attribute of schema must be an " raise AssertionError("the `required` attribute of schema must be an "
"array of required property names, not a boolean!") "array of required property names, not a boolean!")
assert type, "type is required!" assert type, "type is required!"
self.title = title self.title = title
@@ -466,7 +466,7 @@ class Schema(SwaggerDict):
class _Ref(SwaggerDict): class _Ref(SwaggerDict):
ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$") ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$")
def __init__(self, resolver, name, scope, expected_type): def __init__(self, resolver, name, scope, expected_type, ignore_unresolved=False):
"""Base class for all reference types. A reference object has only one property, ``$ref``, which must be a JSON """Base class for all reference types. A reference object has only one property, ``$ref``, which must be a JSON
reference to a valid object in the specification, e.g. ``#/definitions/Article`` to refer to an article model. reference to a valid object in the specification, e.g. ``#/definitions/Article`` to refer to an article model.
@@ -474,13 +474,15 @@ class _Ref(SwaggerDict):
:param str name: referenced object name, e.g. "Article" :param str name: referenced object name, e.g. "Article"
:param str scope: reference scope, e.g. "definitions" :param str scope: reference scope, e.g. "definitions"
:param type[.SwaggerDict] expected_type: the expected type that will be asserted on the object found in resolver :param type[.SwaggerDict] expected_type: the expected type that will be asserted on the object found in resolver
:param bool ignore_unresolved: allow the reference to be not defined in resolver
""" """
super(_Ref, self).__init__() super(_Ref, self).__init__()
assert not type(self) == _Ref, "do not instantiate _Ref directly" assert not type(self) == _Ref, "do not instantiate _Ref directly"
ref_name = "#/{scope}/{name}".format(scope=scope, name=name) ref_name = "#/{scope}/{name}".format(scope=scope, name=name)
obj = resolver.get(name, scope) if not ignore_unresolved:
assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \ obj = resolver.get(name, scope)
.format(actual=type(obj).__name__, expected=expected_type.__name__) assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \
.format(actual=type(obj).__name__, expected=expected_type.__name__)
self.ref = ref_name self.ref = ref_name
def resolve(self, resolver): def resolve(self, resolver):
@@ -502,14 +504,15 @@ class _Ref(SwaggerDict):
class SchemaRef(_Ref): class SchemaRef(_Ref):
def __init__(self, resolver, schema_name): def __init__(self, resolver, schema_name, ignore_unresolved=False):
"""Adds a reference to a named Schema defined in the ``#/definitions/`` object. """Adds a reference to a named Schema defined in the ``#/definitions/`` object.
:param .ReferenceResolver resolver: component resolver which must contain the definition :param .ReferenceResolver resolver: component resolver which must contain the definition
:param str schema_name: schema name :param str schema_name: schema name
:param bool ignore_unresolved: allow the reference to be not defined in resolver
""" """
assert SCHEMA_DEFINITIONS in resolver.scopes assert SCHEMA_DEFINITIONS in resolver.scopes
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema) super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema, ignore_unresolved)
Schema.OR_REF = (Schema, SchemaRef) Schema.OR_REF = (Schema, SchemaRef)
+1
View File
@@ -93,6 +93,7 @@ class _UIRenderer(BaseRenderer):
'defaultModelRendering': swagger_settings.DEFAULT_MODEL_RENDERING, 'defaultModelRendering': swagger_settings.DEFAULT_MODEL_RENDERING,
'defaultModelExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH, 'defaultModelExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
'defaultModelsExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH, 'defaultModelsExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
'showCommonExtensions': swagger_settings.SHOW_COMMON_EXTENSIONS,
'oauth2RedirectUrl': swagger_settings.OAUTH2_REDIRECT_URL, 'oauth2RedirectUrl': swagger_settings.OAUTH2_REDIRECT_URL,
'supportedSubmitMethods': swagger_settings.SUPPORTED_SUBMIT_METHODS, 'supportedSubmitMethods': swagger_settings.SUPPORTED_SUBMIT_METHODS,
} }
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,18 +0,0 @@
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
</head>
<body>
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script>
<script src="{% static 'drf-yasg/redoc-alpha/redoc.standalone.js' %}"> </script>
</body>
</html>
+22
View File
@@ -295,3 +295,25 @@ def decimal_as_float(field):
if isinstance(field, serializers.DecimalField) or isinstance(field, models.DecimalField): if isinstance(field, serializers.DecimalField) or isinstance(field, models.DecimalField):
return not getattr(field, 'coerce_to_string', rest_framework_settings.COERCE_DECIMAL_TO_STRING) return not getattr(field, 'coerce_to_string', rest_framework_settings.COERCE_DECIMAL_TO_STRING)
return False return False
def get_serializer_ref_name(serializer):
"""
Get serializer's ref_name (or None for ModelSerializer if it is named 'NestedSerializer')
:param serializer: Serializer instance
:return: Serializer's ref_name or None for inline serializer
:rtype: str or None
"""
serializer_meta = getattr(serializer, 'Meta', None)
serializer_name = type(serializer).__name__
if hasattr(serializer_meta, 'ref_name'):
ref_name = serializer_meta.ref_name
elif serializer_name == 'NestedSerializer' and isinstance(serializer, serializers.ModelSerializer):
logger.debug("Forcing inline output for ModelSerializer named 'NestedSerializer': " + str(serializer))
ref_name = None
else:
ref_name = serializer_name
if ref_name.endswith('Serializer'):
ref_name = ref_name[:-len('Serializer')]
return ref_name
+22
View File
@@ -0,0 +1,22 @@
# Generated by Django 2.0.4 on 2018-04-26 13:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('todo', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='TodoTree',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('parent', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE,
related_name='children', to='todo.TodoTree')),
],
),
]
+5
View File
@@ -13,3 +13,8 @@ class TodoAnother(models.Model):
class TodoYetAnother(models.Model): class TodoYetAnother(models.Model):
todo = models.ForeignKey(TodoAnother, on_delete=models.CASCADE) todo = models.ForeignKey(TodoAnother, on_delete=models.CASCADE)
title = models.CharField(max_length=50) title = models.CharField(max_length=50)
class TodoTree(models.Model):
parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True)
title = models.CharField(max_length=50)
+21 -1
View File
@@ -1,7 +1,8 @@
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 .models import Todo, TodoAnother, TodoYetAnother from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
class TodoSerializer(serializers.ModelSerializer): class TodoSerializer(serializers.ModelSerializer):
@@ -25,3 +26,22 @@ class TodoYetAnotherSerializer(serializers.ModelSerializer):
model = TodoYetAnother model = TodoYetAnother
fields = ('title', 'todo') fields = ('title', 'todo')
depth = 2 depth = 2
class TodoTreeSerializer(serializers.ModelSerializer):
children = serializers.ListField(child=RecursiveField(), source='children.all')
class Meta:
model = TodoTree
fields = ('id', 'title', 'children')
class TodoRecursiveSerializer(serializers.ModelSerializer):
parent = RecursiveField(read_only=True)
parent_id = serializers.PrimaryKeyRelatedField(queryset=TodoTree.objects.all(), pk_field=serializers.IntegerField(),
write_only=True, allow_null=True, required=False, default=None,
source='parent')
class Meta:
model = TodoTree
fields = ('id', 'title', 'parent', 'parent_id')
+3 -1
View File
@@ -7,10 +7,12 @@ router = routers.DefaultRouter()
router.register(r'', views.TodoViewSet) router.register(r'', views.TodoViewSet)
router.register(r'another', views.TodoAnotherViewSet) router.register(r'another', views.TodoAnotherViewSet)
router.register(r'yetanother', views.TodoYetAnotherViewSet) router.register(r'yetanother', views.TodoYetAnotherViewSet)
router.register(r'tree', views.TodoTreeView)
router.register(r'recursive', views.TodoRecursiveView)
urlpatterns = router.urls urlpatterns = router.urls
urlpatterns += [ urlpatterns += [
url(r'^(?P<todo_id>\d+)/yetanother/(?P<yetanother_id>\d+)/$', url(r'^(?P<todo_id>\d+)/yetanother/(?P<yetanother_id>\d+)/$',
views.NestedTodoView.as_view(),), views.NestedTodoView.as_view(), ),
] ]
+14 -2
View File
@@ -1,8 +1,10 @@
from rest_framework import viewsets from rest_framework import viewsets
from rest_framework.generics import RetrieveAPIView from rest_framework.generics import RetrieveAPIView
from .models import Todo, TodoAnother, TodoYetAnother from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
from .serializer import TodoAnotherSerializer, TodoSerializer, TodoYetAnotherSerializer from .serializer import (
TodoAnotherSerializer, TodoRecursiveSerializer, TodoSerializer, TodoTreeSerializer, TodoYetAnotherSerializer
)
class TodoViewSet(viewsets.ReadOnlyModelViewSet): class TodoViewSet(viewsets.ReadOnlyModelViewSet):
@@ -25,3 +27,13 @@ class TodoYetAnotherViewSet(viewsets.ReadOnlyModelViewSet):
class NestedTodoView(RetrieveAPIView): class NestedTodoView(RetrieveAPIView):
serializer_class = TodoYetAnotherSerializer serializer_class = TodoYetAnotherSerializer
class TodoTreeView(viewsets.ReadOnlyModelViewSet):
queryset = TodoTree.objects.all()
serializer_class = TodoTreeSerializer
class TodoRecursiveView(viewsets.ModelViewSet):
queryset = TodoTree.objects.all()
serializer_class = TodoRecursiveSerializer
+179
View File
@@ -202,6 +202,7 @@ paths:
type: string type: string
pattern: ^69$ pattern: ^69$
default: '69' default: '69'
minLength: 1
- name: image_styles - name: image_styles
in: formData in: formData
description: Parameter with Items description: Parameter with Items
@@ -495,6 +496,129 @@ paths:
description: A unique integer value identifying this todo another. description: A unique integer value identifying this todo another.
required: true required: true
type: integer type: integer
/todo/recursive/:
get:
operationId: todo_recursive_list
description: ''
parameters: []
responses:
'200':
description: ''
schema:
type: array
items:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
post:
operationId: todo_recursive_create
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/TodoRecursive'
responses:
'201':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
parameters: []
/todo/recursive/{id}/:
get:
operationId: todo_recursive_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
put:
operationId: todo_recursive_update
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/TodoRecursive'
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
patch:
operationId: todo_recursive_partial_update
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/TodoRecursive'
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
delete:
operationId: todo_recursive_delete
description: ''
parameters: []
responses:
'204':
description: ''
tags:
- todo
parameters:
- name: id
in: path
description: A unique integer value identifying this todo tree.
required: true
type: integer
/todo/tree/:
get:
operationId: todo_tree_list
description: ''
parameters: []
responses:
'200':
description: ''
schema:
type: array
items:
$ref: '#/definitions/TodoTree'
tags:
- todo
parameters: []
/todo/tree/{id}/:
get:
operationId: todo_tree_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoTree'
tags:
- todo
parameters:
- name: id
in: path
description: A unique integer value identifying this todo tree.
required: true
type: integer
/todo/yetanother/: /todo/yetanother/:
get: get:
operationId: todo_yetanother_list operationId: todo_yetanother_list
@@ -577,6 +701,7 @@ paths:
description: this field is generated from a query_serializer description: this field is generated from a query_serializer
required: false required: false
type: string type: string
minLength: 1
- name: is_staff - name: is_staff
in: query in: query
description: this one too! description: this one too!
@@ -677,6 +802,7 @@ definitions:
description: title model help_text description: title model help_text
type: string type: string
maxLength: 255 maxLength: 255
minLength: 1
author: author:
description: The ID of the user that created this article; if none is provided, description: The ID of the user that created this article; if none is provided,
defaults to the currently logged in user. defaults to the currently logged in user.
@@ -686,6 +812,7 @@ definitions:
description: body serializer help_text description: body serializer help_text
type: string type: string
maxLength: 5000 maxLength: 5000
minLength: 1
slug: slug:
description: slug model help_text description: slug model help_text
type: string type: string
@@ -707,6 +834,7 @@ definitions:
description: but i needed to test these 2 fields somehow description: but i needed to test these 2 fields somehow
type: string type: string
format: uri format: uri
minLength: 1
readOnly: true readOnly: true
uuid: uuid:
description: should articles have UUIDs? description: should articles have UUIDs?
@@ -749,10 +877,12 @@ definitions:
title: FirstName title: FirstName
type: string type: string
maxLength: 30 maxLength: 30
minLength: 1
lastName: lastName:
title: LastName title: LastName
type: string type: string
maxLength: 30 maxLength: 30
minLength: 1
Person: Person:
required: required:
- identity - identity
@@ -774,10 +904,12 @@ definitions:
title: Project name title: Project name
description: Name of the project description: Name of the project
type: string type: string
minLength: 1
githubRepo: githubRepo:
title: Github repo title: Github repo
description: Github repository of the project description: Github repository of the project
type: string type: string
minLength: 1
Snippet: Snippet:
required: required:
- code - code
@@ -799,6 +931,7 @@ definitions:
description: The ID of the user that created this snippet. description: The ID of the user that created this snippet.
type: string type: string
readOnly: true readOnly: true
minLength: 1
title: Owner as string title: Owner as string
title: title:
title: Title title: Title
@@ -807,6 +940,7 @@ definitions:
code: code:
title: Code title: Code
type: string type: string
minLength: 1
linenos: linenos:
title: Linenos title: Linenos
type: boolean type: boolean
@@ -1325,6 +1459,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
TodoAnother: TodoAnother:
required: required:
- title - title
@@ -1335,8 +1470,47 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
todo: todo:
$ref: '#/definitions/Todo' $ref: '#/definitions/Todo'
TodoRecursive:
required:
- title
type: object
properties:
id:
title: ID
type: integer
readOnly: true
title:
title: Title
type: string
maxLength: 50
minLength: 1
parent:
$ref: '#/definitions/TodoRecursive'
parent_id:
type: integer
title: Parent id
TodoTree:
required:
- title
- children
type: object
properties:
id:
title: ID
type: integer
readOnly: true
title:
title: Title
type: string
maxLength: 50
minLength: 1
children:
type: array
items:
$ref: '#/definitions/TodoTree'
TodoYetAnother: TodoYetAnother:
required: required:
- title - title
@@ -1346,6 +1520,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
todo: todo:
required: required:
- title - title
@@ -1359,6 +1534,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
todo: todo:
required: required:
- title - title
@@ -1372,6 +1548,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
readOnly: true readOnly: true
readOnly: true readOnly: true
UserSerializerrr: UserSerializerrr:
@@ -1392,6 +1569,7 @@ definitions:
type: string type: string
pattern: ^[\w.@+-]+$ pattern: ^[\w.@+-]+$
maxLength: 150 maxLength: 150
minLength: 1
email: email:
title: Email address title: Email address
type: string type: string
@@ -1413,6 +1591,7 @@ definitions:
type: string type: string
format: ipv4 format: ipv4
readOnly: true readOnly: true
minLength: 1
last_connected_at: last_connected_at:
title: Last connected at title: Last connected at
description: really? description: really?
+15
View File
@@ -1,3 +1,6 @@
from collections import OrderedDict
from random import shuffle
from drf_yasg import openapi from drf_yasg import openapi
@@ -51,3 +54,15 @@ def test_trailing_underscore_stripped():
del sd.in_ del sd.in_
assert 'in' not in sd assert 'in' not in sd
assert not hasattr(sd, 'in__') assert not hasattr(sd, 'in__')
def test_extra_ordering():
"""Insertion order should also be consistent when setting undeclared parameters (kwargs) in SwaggerDict"""
extras = [('beta', 1), ('alpha', 2), ('omega', 3), ('gamma', 4)]
shuffled_extras = list(extras)
shuffle(shuffled_extras)
s1 = openapi.SwaggerDict(**OrderedDict(extras))
s2 = openapi.SwaggerDict(**OrderedDict(shuffled_extras))
assert list(s1.items()) == list(s2.items())
+3 -3
View File
@@ -65,7 +65,7 @@ known_standard_library =
collections,copy,distutils,functools,inspect,io,json,logging,operator,os,pkg_resources,re,setuptools,sys, collections,copy,distutils,functools,inspect,io,json,logging,operator,os,pkg_resources,re,setuptools,sys,
types,warnings types,warnings
known_third_party = known_third_party =
coreapi,coreschema,datadiff,dj_database_url,django,django_filters,djangorestframework_camel_case,flex,gunicorn, coreapi,coreschema,datadiff,dj_database_url,django,django_filters,djangorestframework_camel_case,
inflection,pygments,pytest,rest_framework,ruamel,setuptools_scm,swagger_spec_validator,uritemplate,user_agents, rest_framework_recursive,flex,gunicorn,inflection,pygments,pytest,rest_framework,ruamel,setuptools_scm,
whitenoise swagger_spec_validator,uritemplate,user_agents,whitenoise
known_first_party = drf_yasg,testproj,articles,people,snippets,todo,users,urlconfs known_first_party = drf_yasg,testproj,articles,people,snippets,todo,users,urlconfs