Compare commits

...

22 Commits

Author SHA1 Message Date
Cristi Vijdea 652a33a54d Fix lint errors 2019-03-04 00:49:28 +02:00
Cristi Vijdea 340a60324c Add special exclusion for FileUploadParser
Fixes #288
2019-03-04 00:48:55 +02:00
Cristi Vijdea f348084d85 Fix Python 2.7 compat 2019-03-04 00:46:00 +02:00
Cristi Vijdea 904c43a167 Add 1.14.0 changelog 2019-03-04 00:08:19 +02:00
Cristi Vijdea 4c78a683f4 Remove Background section from readme 2019-03-03 23:59:12 +02:00
Cristi Vijdea 4da09830ac Add BMaC button (#323) 2019-03-03 23:59:05 +02:00
Cristi Vijdea 34ed1e20a2 Update swagger-ui to 3.21.0 2019-03-03 18:08:25 +02:00
Cristi Vijdea 62d97a80bc Fix _serializer pickle bugs 2019-03-03 17:23:04 +02:00
Cristi Vijdea e108ddbb48 Add force_init argument to ReferenceResolver constructor
Closes #325
2019-03-03 16:40:19 +02:00
Cristi Vijdea 75a5d866be Run makemigrations 2019-03-02 05:51:15 +02:00
Cristi Vijdea f189426901 Update swagger-ui to 3.20.9 2019-03-02 05:42:39 +02:00
Cristi Vijdea b4900ebd6a Add tests for #310 2019-03-02 05:35:10 +02:00
Cristi Vijdea c593b3fcfb Remove _summary_and_description_compat 2019-02-27 21:51:01 +02:00
Cristi Vijdea 9caeed781e Fix duplicate ref_name detection and promote to error 2019-02-27 21:47:31 +02:00
Cristi Vijdea 3377ef08ea Fix Schema limits for ListField and ListSerializer
Fixes #324
2019-02-27 21:23:25 +02:00
Daniel Hahler 5c2c39c82d Travis: use Ubuntu Xenial (#302)
Closes #302
2019-02-27 21:23:09 +02:00
Roman Sichny e538e0713a Support RecursiveField with 'many' option (#321) 2019-02-25 20:59:35 +02:00
Roman Sichny 76c8fe0646 Fix union type hint checks (#318)
Fix some obscure edge cases related to typing.Union type args.

Fixes #304.
2019-02-22 01:00:14 +02:00
Paul Wayper 3d43ee6748 Fix items field conflict with dict.items() (#308)
Closes #307
2019-02-22 00:57:52 +02:00
Cristi Vijdea 583e404ed8 Add xenial hacks back
Travis is still retarded
2019-01-29 09:43:09 +02:00
Cristi Vijdea d62243599b Remove xenial incantations 2019-01-29 09:28:22 +02:00
Cristi Vijdea 6df3523675 Use python 3.7 for lint and Django master tests 2019-01-29 09:26:56 +02:00
24 changed files with 177 additions and 128 deletions
+5 -10
View File
@@ -1,25 +1,22 @@
language: python
sudo: false
python:
- '2.7'
- '3.4'
- '3.5'
- '3.6'
- '3.7'
dist: xenial
cache: pip
jobs:
include:
- # workaround for python 3.7 on travis https://github.com/travis-ci/travis-ci/issues/9815#issuecomment-401756442
stage: test
python: '3.7'
dist: xenial
sudo: required
- python: '3.6'
env: TOXENV=docs
- python: '3.6'
- python: '3.7'
env: TOXENV=djmaster
- python: '3.6'
- python: '3.7'
env: TOXENV=lint
- stage: publish
@@ -66,7 +63,6 @@ after_success:
branches:
only:
- master
- /^release\/.*$/
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
stages:
@@ -74,7 +70,6 @@ stages:
- name: publish
if: tag IS present
notifications:
email:
on_success: always
+11 -42
View File
@@ -7,6 +7,8 @@ drf-yasg - Yet another Swagger generator
|travis| |nbsp| |codecov| |nbsp| |rtd-badge| |nbsp| |pypi-version|
|bmac-button|
Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API.
Compatible with
@@ -29,9 +31,7 @@ Resources:
* **Changelog**: https://drf-yasg.readthedocs.io/en/stable/changelog.html
* **Live demo**: https://drf-yasg-demo.herokuapp.com/
.. image:: https://www.herokucdn.com/deploy/button.svg
:target: https://heroku.com/deploy?template=https://github.com/axnsan12/drf-yasg
:alt: heroku deploy button
|heroku-button|
********
Features
@@ -306,45 +306,6 @@ For additional usage examples, you can take a look at the test project in the ``
(venv) $ python manage.py runserver
(venv) $ firefox localhost:8000/swagger/
**********
Background
**********
``OpenAPI 2.0``/``Swagger`` is a format designed to encode information about a Web API into an easily parsable schema
that can then be used for rendering documentation, generating code, etc.
More details are available on `swagger.io <https://swagger.io/>`__ and on the `OpenAPI 2.0 specification
page <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md>`__.
From here on, the terms “OpenAPI” and “Swagger” are used interchangeably.
Swagger in Django Rest Framework
================================
Since Django Rest Framework 3.7, there is now `built in support <http://www.django-rest-framework.org/api-guide/schemas/>`__
for automatic OpenAPI 2.0 schema generation. However, this generation is based on the `coreapi <http://www.coreapi.org/>`__
standard, which for the moment is vastly inferior to OpenAPI in both features and tooling support. In particular,
the OpenAPI codec/compatibility layer provided has a few major problems:
* there is no support for documenting response schemas and status codes
* nested schemas do not work properly
* does not handle more complex fields such as ``FileField``, ``ChoiceField``, …
In short this makes the generated schema unusable for code generation, and mediocre at best for documentation.
Other libraries
===============
There are currently two decent Swagger schema generators that I could find for django-rest-framework:
* `django-rest-swagger <https://github.com/marcgibbons/django-rest-swagger>`__
* `drf-openapi <https://github.com/limdauto/drf_openapi>`__
``django-rest-swagger`` is just a wrapper around DRF 3.7 schema generation with an added UI, and
thus presents the same problems, while also being unmaintained. ``drf-openapi`` was
`discontinued by the author <https://github.com/limdauto/drf_openapi/commit/1673c6e039eec7f089336a83bdc31613f32f7e21>`_
on April 3rd, 2018.
************************
Third-party integrations
************************
@@ -378,5 +339,13 @@ provided out of the box - if you have ``djangorestframework-recursive`` installe
:target: https://drf-yasg.readthedocs.io/
:alt: ReadTheDocs
.. |bmac-button| image:: https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png
:target: https://www.buymeacoffee.com/cvijdea
:alt: Buy Me A Coffee
.. |heroku-button| image:: https://www.herokucdn.com/deploy/button.svg
:target: https://heroku.com/deploy?template=https://github.com/axnsan12/drf-yasg
:alt: Heroku deploy button
.. |nbsp| unicode:: 0xA0
:trim:
+14 -1
View File
@@ -2,6 +2,19 @@
Changelog
#########
**********
**1.14.0**
**********
*Release date: Mar 04, 2019*
- **IMPROVED:** updated ``swagger-ui`` to version 3.21.0
- **FIXED:** implicit ``ref_name`` collisions will now throw an exception
- **FIXED:** ``RecursiveField`` will now also work as a child of ``ListSerializer`` (:pr:`321`)
- **FIXED:** fixed ``minLength`` and ``maxLength`` for ``ListSerializer`` and ``ListField``
- **FIXED:** the ``items`` property of ``Schema``, ``Parameter`` and ``Items`` objects was renamed to ``items_``; this
is a *mildly breaking change* and was needed to fix the collision with the ``items`` method of ``dict`` (:pr:`308`)
- **REMOVED:** the ``get_summary`` and ``get_description`` methods have been removed (previously deprecated in 1.12.0)
**********
**1.13.0**
@@ -9,7 +22,7 @@ Changelog
*Release date: Jan 29, 2019*
- **IMPROVED:** type hint inspection is now supported for collections and``Optional`` (:pr:`272`)
- **IMPROVED:** type hint inspection is now supported for collections and ``Optional`` (:pr:`272`)
- **IMPROVED:** updated ``swagger-ui`` to version 3.20.5
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-rc.2
- **DEPRECATED:** quietly dropped support for the ``flex`` validator; it will still work if the library is installed,
+5 -5
View File
@@ -156,7 +156,7 @@
},
"json5": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
"resolved": "http://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
"integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
"requires": {
"minimist": "^1.2.0"
@@ -215,7 +215,7 @@
},
"minimist": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ="
},
"mobx-react": {
@@ -399,9 +399,9 @@
"integrity": "sha1-OUE/7p0CXHSn5ZzuyyN4TMDxfwI="
},
"swagger-ui-dist": {
"version": "3.20.5",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.20.5.tgz",
"integrity": "sha512-DNmJQ1qVkW8xk3wI2VfupOS7IYTHNjYaYX+L4s8B8ksdtoHOx3RsRqJUMIQByojHgb3PwEt+zGdIUwxJ4N5pwg=="
"version": "3.21.0",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.21.0.tgz",
"integrity": "sha512-bAhzzpujhSIXdzpSI9b9RpvahC556lxcOIXxt1OOtTIasYodpy94gDlanQl4j7xavmi4nhaGiZ9iBcoFO+wHlA=="
},
"tiny-emitter": {
"version": "2.0.2",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "drf-yasg",
"dependencies": {
"redoc": "^2.0.0-rc.2",
"swagger-ui-dist": "^3.20.5"
"swagger-ui-dist": "^3.21.0"
},
"repository": {
"type": "git",
+1 -1
View File
@@ -238,7 +238,7 @@ class OpenAPISchemaGenerator(object):
:rtype: openapi.Swagger
"""
endpoints = self.get_endpoints(request)
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS, force_init=True)
self.consumes = get_consumes(api_settings.DEFAULT_PARSER_CLASSES)
self.produces = get_produces(api_settings.DEFAULT_RENDERER_CLASSES)
paths, prefix = self.get_paths(endpoints, components, request, public)
+44 -10
View File
@@ -72,14 +72,20 @@ class InlineSerializerInspector(SerializerInspector):
def get_serializer_ref_name(self, serializer):
return get_serializer_ref_name(serializer)
def _has_ref_name(self, serializer):
serializer_meta = getattr(serializer, 'Meta', None)
return hasattr(serializer_meta, 'ref_name')
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)
if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
child_schema = self.probe_field_inspectors(field.child, ChildSwaggerType, use_references)
limits = find_limits(field) or {}
return SwaggerType(
type=openapi.TYPE_ARRAY,
items=child_schema,
**limits
)
elif isinstance(field, serializers.Serializer):
if swagger_object_type != openapi.Schema:
@@ -116,6 +122,7 @@ class InlineSerializerInspector(SerializerInspector):
# it is better to just remove title from inline models
del result.title
setattr(result, '_NP_serializer', get_serializer_class(serializer))
return result
if not ref_name or not use_references:
@@ -125,11 +132,15 @@ class InlineSerializerInspector(SerializerInspector):
actual_schema = definitions.setdefault(ref_name, make_schema_definition)
actual_schema._remove_read_only()
actual_serializer = get_serializer_class(getattr(actual_schema, '_serializer', None))
actual_serializer = getattr(actual_schema, '_NP_serializer', None)
this_serializer = get_serializer_class(field)
if actual_serializer and actual_serializer != this_serializer: # pragma: no cover
logger.warning("Schema for %s will override distinct serializer %s because they "
"share the same ref_name", actual_serializer, this_serializer)
explicit_refs = self._has_ref_name(actual_serializer) and self._has_ref_name(this_serializer)
if not explicit_refs:
raise SwaggerGenerationError(
"Schema for %s would override distinct serializer %s because they implicitly share the same "
"ref_name; explicitly set the ref_name atribute on both serializers' Meta classes"
% (actual_serializer, this_serializer))
return openapi.SchemaRef(definitions, ref_name)
@@ -490,6 +501,20 @@ if typing:
hinting_type_info.append(((typing.Sequence, typing.AbstractSet), inspect_collection_hint_class))
def _get_union_types(hint_class):
if typing:
origin_type = get_origin_type(hint_class)
if origin_type is typing.Union:
return hint_class.__args__
try:
# python 3.5.2 and lower compatibility
if issubclass(origin_type, typing.Union):
return hint_class.__union_params__
except TypeError:
pass
return None
def get_basic_type_info_from_hint(hint_class):
"""Given a class (eg from a SerializerMethodField's return type hint,
return its basic type information - ``type``, ``format``, ``pattern``,
@@ -499,11 +524,11 @@ def get_basic_type_info_from_hint(hint_class):
:return: the extracted attributes as a dictionary, or ``None`` if the field type is not known
:rtype: OrderedDict
"""
if typing and get_origin_type(hint_class) == typing.Union:
union_types = _get_union_types(hint_class)
if typing and union_types:
# Optional is implemented as Union[T, None]
if len(hint_class.__args__) == 2 and hint_class.__args__[1] == type(None): # noqa: E721
child_type = hint_class.__args__[0]
result = get_basic_type_info_from_hint(child_type)
if len(union_types) == 2 and isinstance(None, union_types[1]):
result = get_basic_type_info_from_hint(union_types[0])
result['x-nullable'] = True
return result
@@ -780,10 +805,19 @@ else:
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't create RecursiveField schema for inline " + str(type(field.proxied))
proxied = field.proxied
if isinstance(field.proxied, serializers.ListSerializer):
proxied = proxied.child
ref_name = get_serializer_ref_name(proxied)
assert ref_name is not None, "Can't create RecursiveField schema for inline " + str(type(proxied))
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
return openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)
ref = openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)
if isinstance(field.proxied, serializers.ListSerializer):
ref = openapi.Items(type=openapi.TYPE_ARRAY, items=ref)
return ref
return NotHandled
-27
View File
@@ -21,17 +21,6 @@ class SwaggerAutoSchema(ViewInspector):
super(SwaggerAutoSchema, self).__init__(view, path, method, components, request, overrides)
self._sch = AutoSchema()
self._sch.view = view
self._summary_and_description_compat()
def _summary_and_description_compat(self):
# TODO: remove in 1.14
base_methods = (SwaggerAutoSchema.get_summary, SwaggerAutoSchema.get_description)
self_methods = (type(self).get_summary, type(self).get_description)
if self_methods != base_methods:
raise NotImplementedError(
"`SwaggerAutoSchema` methods `get_summary` and `get_description` were removed in "
"drf-yasg 1.13 and will have no effect. Override `get_summary_and_description` instead."
)
def get_operation(self, operation_keys):
consumes = self.get_consumes()
@@ -362,22 +351,6 @@ class SwaggerAutoSchema(ViewInspector):
return summary, description
def get_summary(self):
"""Return a summary description for this operation.
:return: the summary
:rtype: str
"""
return self.get_summary_and_description()[0]
def get_description(self):
"""Return an operation description determined as appropriate from the view's method and class docstrings.
:return: the operation description
:rtype: str
"""
return self.get_summary_and_description()[1]
def get_security(self):
"""Return a list of security requirements for this operation.
+18 -7
View File
@@ -167,7 +167,8 @@ class SwaggerDict(OrderedDict):
def __reduce__(self):
# for pickle supprt; this skips calls to all SwaggerDict __init__ methods and relies
# on the already set attributes instead
return _bare_SwaggerDict, (type(self),), vars(self), None, iter(self.items())
attrs = {k: v for k, v in vars(self).items() if not k.startswith('_NP_')}
return _bare_SwaggerDict, (type(self),), attrs, None, iter(self.items())
class Contact(SwaggerDict):
@@ -400,7 +401,7 @@ class Items(SwaggerDict):
self.format = format
self.enum = enum
self.pattern = pattern
self.items = items
self.items_ = items
self._insert_extras__()
_check_type(type, format, enum, pattern, items, self.__class__)
@@ -434,7 +435,7 @@ class Parameter(SwaggerDict):
self.format = format
self.enum = enum
self.pattern = pattern
self.items = items
self.items_ = items
self.default = default
self._insert_extras__()
if (not schema and not type) or (schema and type):
@@ -492,7 +493,7 @@ class Schema(SwaggerDict):
self.format = format
self.enum = enum
self.pattern = pattern
self.items = items
self.items_ = items
self.read_only = read_only
self.default = default
self._insert_extras__()
@@ -617,16 +618,26 @@ class ReferenceResolver(object):
::
> components = ReferenceResolver('definitions', 'parameters')
> definitions = ReferenceResolver.with_scope('definitions')
> definitions = components.with_scope('definitions')
> definitions.set('Article', Schema(...))
> print(components)
{'definitions': OrderedDict([('Article', Schema(...)]), 'parameters': OrderedDict()}
"""
def __init__(self, *scopes):
def __init__(self, *scopes, **kwargs):
"""
:param str scopes: an enumeration of the valid scopes this resolver will contain
"""
force_init = kwargs.pop('force_init', False)
if not force_init:
raise AssertionError(
"Creating an instance of ReferenceResolver almost certainly won't do what you want it to do.\n"
"See https://github.com/axnsan12/drf-yasg/issues/211, "
"https://github.com/axnsan12/drf-yasg/issues/271, "
"https://github.com/axnsan12/drf-yasg/issues/325.\n"
"Pass `force_init=True` to override this."
)
self._objects = OrderedDict()
self._force_scope = None
for scope in scopes:
@@ -641,7 +652,7 @@ class ReferenceResolver(object):
:rtype: .ReferenceResolver
"""
assert scope in self.scopes, "unknown scope %s" % scope
ret = ReferenceResolver()
ret = ReferenceResolver(force_init=True)
ret._objects = self._objects
ret._force_scope = scope
return ret
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 628 B

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
+2
View File
@@ -7,6 +7,7 @@ from django.db import models
from django.utils.encoding import force_text
from rest_framework import serializers, status
from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.parsers import FileUploadParser
from rest_framework.request import is_form_media_type
from rest_framework.settings import api_settings as rest_framework_settings
from rest_framework.utils import encoders, json
@@ -366,6 +367,7 @@ def get_consumes(parser_classes):
:rtype: list[str]
"""
parser_classes = get_object_classes(parser_classes)
parser_classes = [pc for pc in parser_classes if not issubclass(pc, FileUploadParser)]
media_types = [parser.media_type for parser in parser_classes or []]
non_form_media_types = [encoding for encoding in media_types if not is_form_media_type(encoding)]
if len(non_form_media_types) == 0:
@@ -0,0 +1,18 @@
# Generated by Django 2.1.5 on 2019-03-02 03:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='article',
name='read_only_nullable',
field=models.CharField(blank=True, max_length=20, null=True),
),
]
+1
View File
@@ -20,6 +20,7 @@ class Article(models.Model):
on_delete=models.PROTECT)
original_group = models.ForeignKey('ArticleGroup', related_name='articles_as_original', blank=True, default=None,
on_delete=models.PROTECT)
read_only_nullable = models.CharField(max_length=20, null=True, blank=True)
class ArticleGroup(models.Model):
+3 -3
View File
@@ -17,10 +17,9 @@ class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('title', 'author', 'body', 'slug', 'date_created', 'date_modified',
fields = ('title', 'author', 'body', 'slug', 'date_created', 'date_modified', 'read_only_nullable',
'references', 'uuid', 'cover', 'cover_name', 'article_type', 'group', 'original_group', )
read_only_fields = ('date_created', 'date_modified',
'references', 'uuid', 'cover_name')
read_only_fields = ('date_created', 'date_modified', 'references', 'uuid', 'cover_name', 'read_only_nullable')
lookup_field = 'slug'
extra_kwargs = {
'body': {'help_text': 'body serializer help_text'},
@@ -29,6 +28,7 @@ class ArticleSerializer(serializers.ModelSerializer):
'help_text': _("The ID of the user that created this article; if none is provided, "
"defaults to the currently logged in user.")
},
'read_only_nullable': {'allow_null': True},
}
+2 -2
View File
@@ -7,7 +7,7 @@ from rest_framework import viewsets
# noinspection PyDeprecation
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.parsers import MultiPartParser
from rest_framework.parsers import MultiPartParser, FileUploadParser
from rest_framework.response import Response
from articles import serializers
@@ -118,7 +118,7 @@ class ArticleViewSet(viewsets.ModelViewSet):
type=openapi.TYPE_INTEGER,
description="this should not crash (form parameter on DELETE method)"
)])
@detail_route(methods=['get', 'post', 'delete'], parser_classes=(MultiPartParser,))
@detail_route(methods=['get', 'post', 'delete'], parser_classes=(MultiPartParser, FileUploadParser))
def image(self, request, slug=None):
"""
image method docstring
+5 -2
View File
@@ -2,7 +2,7 @@ from decimal import Decimal
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.compat import MinValueValidator
from rest_framework.compat import MaxLengthValidator, MinValueValidator
from snippets.models import LANGUAGE_CHOICES, STYLE_CHOICES, Snippet
@@ -10,6 +10,7 @@ from snippets.models import LANGUAGE_CHOICES, STYLE_CHOICES, Snippet
class LanguageSerializer(serializers.Serializer):
name = serializers.ChoiceField(
choices=LANGUAGE_CHOICES, default='python', help_text='The name of the programming language')
read_only_nullable = serializers.CharField(read_only=True, allow_null=True)
class Meta:
ref_name = None
@@ -65,11 +66,13 @@ class SnippetSerializer(serializers.Serializer):
)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
tags = serializers.ListField(child=serializers.CharField(min_length=2), min_length=3, max_length=15)
linenos = serializers.BooleanField(required=False)
language = LanguageSerializer(help_text="Sample help text for language")
styles = serializers.MultipleChoiceField(choices=STYLE_CHOICES, default=['friendly'])
lines = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, allow_null=True, required=False)
example_projects = serializers.ListSerializer(child=ExampleProjectSerializer(), read_only=True)
example_projects = serializers.ListSerializer(child=ExampleProjectSerializer(), read_only=True,
validators=[MaxLengthValidator(100)])
difficulty_factor = serializers.FloatField(help_text="this is here just to test FloatField",
read_only=True, default=lambda: 6.9)
rate_as_string = serializers.DecimalField(max_digits=6, decimal_places=3, default=Decimal('0.0'),
+2 -2
View File
@@ -2,7 +2,7 @@ from djangorestframework_camel_case.parser import CamelCaseJSONParser
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
from inflection import camelize
from rest_framework import generics, status
from rest_framework.parsers import FormParser
from rest_framework.parsers import FormParser, FileUploadParser
from drf_yasg import openapi
from drf_yasg.inspectors import SwaggerAutoSchema
@@ -22,7 +22,7 @@ class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
parser_classes = (FormParser, CamelCaseJSONParser,)
parser_classes = (FormParser, CamelCaseJSONParser, FileUploadParser)
renderer_classes = (CamelCaseJSONRenderer,)
swagger_schema = CamelCaseOperationIDAutoSchema
+2 -1
View File
@@ -41,10 +41,11 @@ class TodoYetAnotherSerializer(serializers.ModelSerializer):
class TodoTreeSerializer(serializers.ModelSerializer):
children = serializers.ListField(child=RecursiveField(), source='children.all')
many_children = RecursiveField(many=True, source='children')
class Meta:
model = TodoTree
fields = ('id', 'title', 'children')
fields = ('id', 'title', 'children', 'many_children')
class TodoRecursiveSerializer(serializers.ModelSerializer):
+25
View File
@@ -902,6 +902,11 @@ definitions:
type: string
format: date-time
readOnly: true
read_only_nullable:
type: string
readOnly: true
minLength: 1
x-nullable: true
references:
description: this is a really bad example
type: object
@@ -1023,6 +1028,7 @@ definitions:
Snippet:
required:
- code
- tags
- language
type: object
properties:
@@ -1057,6 +1063,13 @@ definitions:
title: Code
type: string
minLength: 1
tags:
type: array
items:
type: string
minLength: 2
maxItems: 15
minItems: 3
linenos:
title: Linenos
type: boolean
@@ -1507,6 +1520,12 @@ definitions:
- yaml+jinja
- zephir
default: python
readOnlyNullable:
title: Read only nullable
type: string
readOnly: true
minLength: 1
x-nullable: true
styles:
type: array
items:
@@ -1553,6 +1572,7 @@ definitions:
items:
$ref: '#/definitions/Project'
readOnly: true
maxItems: 100
difficultyFactor:
title: Difficulty factor
description: this is here just to test FloatField
@@ -1617,6 +1637,7 @@ definitions:
required:
- title
- children
- many_children
type: object
properties:
id:
@@ -1632,6 +1653,10 @@ definitions:
type: array
items:
$ref: '#/definitions/TodoTree'
many_children:
type: array
items:
$ref: '#/definitions/TodoTree'
TodoYetAnother:
required:
- title
@@ -33,6 +33,10 @@ if typing:
# Following cases are not 100% correct, but it should work somehow and not crash.
(Union[int, float], None),
(List, {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_STRING)}),
('SomeType', None),
(type('SomeType', (object,), {}), None),
(None, None),
(6, None),
])
def test_get_basic_type_info_from_hint(hint_class, expected_swagger_type_info):
type_info = get_basic_type_info_from_hint(hint_class)
+2 -2
View File
@@ -5,7 +5,7 @@ from drf_yasg.openapi import ReferenceResolver
def test_basic():
scopes = ['s1', 's2']
rr = ReferenceResolver(*scopes)
rr = ReferenceResolver(*scopes, force_init=True)
assert scopes == rr.scopes == list(rr.keys()) == list(rr)
rr.set('o1', 1, scope='s1')
assert rr.has('o1', scope='s1')
@@ -25,7 +25,7 @@ def test_basic():
def test_scoped():
scopes = ['s1', 's2']
rr = ReferenceResolver(*scopes)
rr = ReferenceResolver(*scopes, force_init=True)
r1 = rr.with_scope('s1')
r2 = rr.with_scope('s2')
with pytest.raises(AssertionError):