Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 652a33a54d | |||
| 340a60324c | |||
| f348084d85 | |||
| 904c43a167 | |||
| 4c78a683f4 | |||
| 4da09830ac | |||
| 34ed1e20a2 | |||
| 62d97a80bc | |||
| e108ddbb48 | |||
| 75a5d866be | |||
| f189426901 | |||
| b4900ebd6a | |||
| c593b3fcfb | |||
| 9caeed781e | |||
| 3377ef08ea | |||
| 5c2c39c82d | |||
| e538e0713a | |||
| 76c8fe0646 | |||
| 3d43ee6748 | |||
| 583e404ed8 | |||
| d62243599b | |||
| 6df3523675 |
+5
-10
@@ -1,25 +1,22 @@
|
|||||||
language: python
|
language: python
|
||||||
sudo: false
|
|
||||||
python:
|
python:
|
||||||
- '2.7'
|
- '2.7'
|
||||||
- '3.4'
|
- '3.4'
|
||||||
- '3.5'
|
- '3.5'
|
||||||
- '3.6'
|
- '3.6'
|
||||||
|
- '3.7'
|
||||||
|
|
||||||
|
dist: xenial
|
||||||
|
|
||||||
cache: pip
|
cache: pip
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
include:
|
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'
|
- python: '3.6'
|
||||||
env: TOXENV=docs
|
env: TOXENV=docs
|
||||||
- python: '3.6'
|
- python: '3.7'
|
||||||
env: TOXENV=djmaster
|
env: TOXENV=djmaster
|
||||||
- python: '3.6'
|
- python: '3.7'
|
||||||
env: TOXENV=lint
|
env: TOXENV=lint
|
||||||
|
|
||||||
- stage: publish
|
- stage: publish
|
||||||
@@ -66,7 +63,6 @@ after_success:
|
|||||||
branches:
|
branches:
|
||||||
only:
|
only:
|
||||||
- master
|
- master
|
||||||
- /^release\/.*$/
|
|
||||||
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
|
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
|
||||||
|
|
||||||
stages:
|
stages:
|
||||||
@@ -74,7 +70,6 @@ stages:
|
|||||||
- name: publish
|
- name: publish
|
||||||
if: tag IS present
|
if: tag IS present
|
||||||
|
|
||||||
|
|
||||||
notifications:
|
notifications:
|
||||||
email:
|
email:
|
||||||
on_success: always
|
on_success: always
|
||||||
|
|||||||
+11
-42
@@ -7,6 +7,8 @@ drf-yasg - Yet another Swagger generator
|
|||||||
|
|
||||||
|travis| |nbsp| |codecov| |nbsp| |rtd-badge| |nbsp| |pypi-version|
|
|travis| |nbsp| |codecov| |nbsp| |rtd-badge| |nbsp| |pypi-version|
|
||||||
|
|
||||||
|
|bmac-button|
|
||||||
|
|
||||||
Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API.
|
Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API.
|
||||||
|
|
||||||
Compatible with
|
Compatible with
|
||||||
@@ -29,9 +31,7 @@ Resources:
|
|||||||
* **Changelog**: https://drf-yasg.readthedocs.io/en/stable/changelog.html
|
* **Changelog**: https://drf-yasg.readthedocs.io/en/stable/changelog.html
|
||||||
* **Live demo**: https://drf-yasg-demo.herokuapp.com/
|
* **Live demo**: https://drf-yasg-demo.herokuapp.com/
|
||||||
|
|
||||||
.. image:: https://www.herokucdn.com/deploy/button.svg
|
|heroku-button|
|
||||||
:target: https://heroku.com/deploy?template=https://github.com/axnsan12/drf-yasg
|
|
||||||
:alt: heroku deploy button
|
|
||||||
|
|
||||||
********
|
********
|
||||||
Features
|
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) $ python manage.py runserver
|
||||||
(venv) $ firefox localhost:8000/swagger/
|
(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
|
Third-party integrations
|
||||||
************************
|
************************
|
||||||
@@ -378,5 +339,13 @@ provided out of the box - if you have ``djangorestframework-recursive`` installe
|
|||||||
:target: https://drf-yasg.readthedocs.io/
|
:target: https://drf-yasg.readthedocs.io/
|
||||||
:alt: ReadTheDocs
|
: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
|
.. |nbsp| unicode:: 0xA0
|
||||||
:trim:
|
:trim:
|
||||||
|
|||||||
+14
-1
@@ -2,6 +2,19 @@
|
|||||||
Changelog
|
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**
|
**1.13.0**
|
||||||
@@ -9,7 +22,7 @@ Changelog
|
|||||||
|
|
||||||
*Release date: Jan 29, 2019*
|
*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 ``swagger-ui`` to version 3.20.5
|
||||||
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-rc.2
|
- **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,
|
- **DEPRECATED:** quietly dropped support for the ``flex`` validator; it will still work if the library is installed,
|
||||||
|
|||||||
Generated
+5
-5
@@ -156,7 +156,7 @@
|
|||||||
},
|
},
|
||||||
"json5": {
|
"json5": {
|
||||||
"version": "1.0.1",
|
"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==",
|
"integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
|
||||||
"requires": {
|
"requires": {
|
||||||
"minimist": "^1.2.0"
|
"minimist": "^1.2.0"
|
||||||
@@ -215,7 +215,7 @@
|
|||||||
},
|
},
|
||||||
"minimist": {
|
"minimist": {
|
||||||
"version": "1.2.0",
|
"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="
|
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ="
|
||||||
},
|
},
|
||||||
"mobx-react": {
|
"mobx-react": {
|
||||||
@@ -399,9 +399,9 @@
|
|||||||
"integrity": "sha1-OUE/7p0CXHSn5ZzuyyN4TMDxfwI="
|
"integrity": "sha1-OUE/7p0CXHSn5ZzuyyN4TMDxfwI="
|
||||||
},
|
},
|
||||||
"swagger-ui-dist": {
|
"swagger-ui-dist": {
|
||||||
"version": "3.20.5",
|
"version": "3.21.0",
|
||||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.20.5.tgz",
|
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.21.0.tgz",
|
||||||
"integrity": "sha512-DNmJQ1qVkW8xk3wI2VfupOS7IYTHNjYaYX+L4s8B8ksdtoHOx3RsRqJUMIQByojHgb3PwEt+zGdIUwxJ4N5pwg=="
|
"integrity": "sha512-bAhzzpujhSIXdzpSI9b9RpvahC556lxcOIXxt1OOtTIasYodpy94gDlanQl4j7xavmi4nhaGiZ9iBcoFO+wHlA=="
|
||||||
},
|
},
|
||||||
"tiny-emitter": {
|
"tiny-emitter": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
"name": "drf-yasg",
|
"name": "drf-yasg",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"redoc": "^2.0.0-rc.2",
|
"redoc": "^2.0.0-rc.2",
|
||||||
"swagger-ui-dist": "^3.20.5"
|
"swagger-ui-dist": "^3.21.0"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
@@ -238,7 +238,7 @@ class OpenAPISchemaGenerator(object):
|
|||||||
:rtype: openapi.Swagger
|
:rtype: openapi.Swagger
|
||||||
"""
|
"""
|
||||||
endpoints = self.get_endpoints(request)
|
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.consumes = get_consumes(api_settings.DEFAULT_PARSER_CLASSES)
|
||||||
self.produces = get_produces(api_settings.DEFAULT_RENDERER_CLASSES)
|
self.produces = get_produces(api_settings.DEFAULT_RENDERER_CLASSES)
|
||||||
paths, prefix = self.get_paths(endpoints, components, request, public)
|
paths, prefix = self.get_paths(endpoints, components, request, public)
|
||||||
|
|||||||
@@ -72,14 +72,20 @@ class InlineSerializerInspector(SerializerInspector):
|
|||||||
def get_serializer_ref_name(self, serializer):
|
def get_serializer_ref_name(self, serializer):
|
||||||
return get_serializer_ref_name(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):
|
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)
|
||||||
|
|
||||||
if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
|
if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
|
||||||
child_schema = self.probe_field_inspectors(field.child, ChildSwaggerType, use_references)
|
child_schema = self.probe_field_inspectors(field.child, ChildSwaggerType, use_references)
|
||||||
|
limits = find_limits(field) or {}
|
||||||
return SwaggerType(
|
return SwaggerType(
|
||||||
type=openapi.TYPE_ARRAY,
|
type=openapi.TYPE_ARRAY,
|
||||||
items=child_schema,
|
items=child_schema,
|
||||||
|
**limits
|
||||||
)
|
)
|
||||||
elif isinstance(field, serializers.Serializer):
|
elif isinstance(field, serializers.Serializer):
|
||||||
if swagger_object_type != openapi.Schema:
|
if swagger_object_type != openapi.Schema:
|
||||||
@@ -116,6 +122,7 @@ class InlineSerializerInspector(SerializerInspector):
|
|||||||
# it is better to just remove title from inline models
|
# it is better to just remove title from inline models
|
||||||
del result.title
|
del result.title
|
||||||
|
|
||||||
|
setattr(result, '_NP_serializer', get_serializer_class(serializer))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
if not ref_name or not use_references:
|
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 = definitions.setdefault(ref_name, make_schema_definition)
|
||||||
actual_schema._remove_read_only()
|
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)
|
this_serializer = get_serializer_class(field)
|
||||||
if actual_serializer and actual_serializer != this_serializer: # pragma: no cover
|
if actual_serializer and actual_serializer != this_serializer: # pragma: no cover
|
||||||
logger.warning("Schema for %s will override distinct serializer %s because they "
|
explicit_refs = self._has_ref_name(actual_serializer) and self._has_ref_name(this_serializer)
|
||||||
"share the same ref_name", actual_serializer, 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)
|
return openapi.SchemaRef(definitions, ref_name)
|
||||||
|
|
||||||
@@ -490,6 +501,20 @@ if typing:
|
|||||||
hinting_type_info.append(((typing.Sequence, typing.AbstractSet), inspect_collection_hint_class))
|
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):
|
def get_basic_type_info_from_hint(hint_class):
|
||||||
"""Given a class (eg from a SerializerMethodField's return type hint,
|
"""Given a class (eg from a SerializerMethodField's return type hint,
|
||||||
return its basic type information - ``type``, ``format``, ``pattern``,
|
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
|
:return: the extracted attributes as a dictionary, or ``None`` if the field type is not known
|
||||||
:rtype: OrderedDict
|
: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]
|
# Optional is implemented as Union[T, None]
|
||||||
if len(hint_class.__args__) == 2 and hint_class.__args__[1] == type(None): # noqa: E721
|
if len(union_types) == 2 and isinstance(None, union_types[1]):
|
||||||
child_type = hint_class.__args__[0]
|
result = get_basic_type_info_from_hint(union_types[0])
|
||||||
result = get_basic_type_info_from_hint(child_type)
|
|
||||||
result['x-nullable'] = True
|
result['x-nullable'] = True
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -780,10 +805,19 @@ else:
|
|||||||
if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema:
|
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"
|
assert use_references is True, "Can not create schema for RecursiveField when use_references is False"
|
||||||
|
|
||||||
ref_name = get_serializer_ref_name(field.proxied)
|
proxied = field.proxied
|
||||||
assert ref_name is not None, "Can't create RecursiveField schema for inline " + str(type(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)
|
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
|
return NotHandled
|
||||||
|
|||||||
@@ -21,17 +21,6 @@ class SwaggerAutoSchema(ViewInspector):
|
|||||||
super(SwaggerAutoSchema, self).__init__(view, path, method, components, request, overrides)
|
super(SwaggerAutoSchema, self).__init__(view, path, method, components, request, overrides)
|
||||||
self._sch = AutoSchema()
|
self._sch = AutoSchema()
|
||||||
self._sch.view = view
|
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):
|
def get_operation(self, operation_keys):
|
||||||
consumes = self.get_consumes()
|
consumes = self.get_consumes()
|
||||||
@@ -362,22 +351,6 @@ class SwaggerAutoSchema(ViewInspector):
|
|||||||
|
|
||||||
return summary, description
|
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):
|
def get_security(self):
|
||||||
"""Return a list of security requirements for this operation.
|
"""Return a list of security requirements for this operation.
|
||||||
|
|
||||||
|
|||||||
+18
-7
@@ -167,7 +167,8 @@ class SwaggerDict(OrderedDict):
|
|||||||
def __reduce__(self):
|
def __reduce__(self):
|
||||||
# for pickle supprt; this skips calls to all SwaggerDict __init__ methods and relies
|
# for pickle supprt; this skips calls to all SwaggerDict __init__ methods and relies
|
||||||
# on the already set attributes instead
|
# 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):
|
class Contact(SwaggerDict):
|
||||||
@@ -400,7 +401,7 @@ class Items(SwaggerDict):
|
|||||||
self.format = format
|
self.format = format
|
||||||
self.enum = enum
|
self.enum = enum
|
||||||
self.pattern = pattern
|
self.pattern = pattern
|
||||||
self.items = items
|
self.items_ = items
|
||||||
self._insert_extras__()
|
self._insert_extras__()
|
||||||
_check_type(type, format, enum, pattern, items, self.__class__)
|
_check_type(type, format, enum, pattern, items, self.__class__)
|
||||||
|
|
||||||
@@ -434,7 +435,7 @@ class Parameter(SwaggerDict):
|
|||||||
self.format = format
|
self.format = format
|
||||||
self.enum = enum
|
self.enum = enum
|
||||||
self.pattern = pattern
|
self.pattern = pattern
|
||||||
self.items = items
|
self.items_ = items
|
||||||
self.default = default
|
self.default = default
|
||||||
self._insert_extras__()
|
self._insert_extras__()
|
||||||
if (not schema and not type) or (schema and type):
|
if (not schema and not type) or (schema and type):
|
||||||
@@ -492,7 +493,7 @@ class Schema(SwaggerDict):
|
|||||||
self.format = format
|
self.format = format
|
||||||
self.enum = enum
|
self.enum = enum
|
||||||
self.pattern = pattern
|
self.pattern = pattern
|
||||||
self.items = items
|
self.items_ = items
|
||||||
self.read_only = read_only
|
self.read_only = read_only
|
||||||
self.default = default
|
self.default = default
|
||||||
self._insert_extras__()
|
self._insert_extras__()
|
||||||
@@ -617,16 +618,26 @@ class ReferenceResolver(object):
|
|||||||
::
|
::
|
||||||
|
|
||||||
> components = ReferenceResolver('definitions', 'parameters')
|
> components = ReferenceResolver('definitions', 'parameters')
|
||||||
> definitions = ReferenceResolver.with_scope('definitions')
|
> definitions = components.with_scope('definitions')
|
||||||
> definitions.set('Article', Schema(...))
|
> definitions.set('Article', Schema(...))
|
||||||
> print(components)
|
> print(components)
|
||||||
{'definitions': OrderedDict([('Article', Schema(...)]), 'parameters': OrderedDict()}
|
{'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
|
: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._objects = OrderedDict()
|
||||||
self._force_scope = None
|
self._force_scope = None
|
||||||
for scope in scopes:
|
for scope in scopes:
|
||||||
@@ -641,7 +652,7 @@ class ReferenceResolver(object):
|
|||||||
:rtype: .ReferenceResolver
|
:rtype: .ReferenceResolver
|
||||||
"""
|
"""
|
||||||
assert scope in self.scopes, "unknown scope %s" % scope
|
assert scope in self.scopes, "unknown scope %s" % scope
|
||||||
ret = ReferenceResolver()
|
ret = ReferenceResolver(force_init=True)
|
||||||
ret._objects = self._objects
|
ret._objects = self._objects
|
||||||
ret._force_scope = scope
|
ret._force_scope = scope
|
||||||
return ret
|
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
@@ -7,6 +7,7 @@ from django.db import models
|
|||||||
from django.utils.encoding import force_text
|
from django.utils.encoding import force_text
|
||||||
from rest_framework import serializers, status
|
from rest_framework import serializers, status
|
||||||
from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin
|
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.request import is_form_media_type
|
||||||
from rest_framework.settings import api_settings as rest_framework_settings
|
from rest_framework.settings import api_settings as rest_framework_settings
|
||||||
from rest_framework.utils import encoders, json
|
from rest_framework.utils import encoders, json
|
||||||
@@ -366,6 +367,7 @@ def get_consumes(parser_classes):
|
|||||||
:rtype: list[str]
|
:rtype: list[str]
|
||||||
"""
|
"""
|
||||||
parser_classes = get_object_classes(parser_classes)
|
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 []]
|
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)]
|
non_form_media_types = [encoding for encoding in media_types if not is_form_media_type(encoding)]
|
||||||
if len(non_form_media_types) == 0:
|
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),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -20,6 +20,7 @@ class Article(models.Model):
|
|||||||
on_delete=models.PROTECT)
|
on_delete=models.PROTECT)
|
||||||
original_group = models.ForeignKey('ArticleGroup', related_name='articles_as_original', blank=True, default=None,
|
original_group = models.ForeignKey('ArticleGroup', related_name='articles_as_original', blank=True, default=None,
|
||||||
on_delete=models.PROTECT)
|
on_delete=models.PROTECT)
|
||||||
|
read_only_nullable = models.CharField(max_length=20, null=True, blank=True)
|
||||||
|
|
||||||
|
|
||||||
class ArticleGroup(models.Model):
|
class ArticleGroup(models.Model):
|
||||||
|
|||||||
@@ -17,10 +17,9 @@ class ArticleSerializer(serializers.ModelSerializer):
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Article
|
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', )
|
'references', 'uuid', 'cover', 'cover_name', 'article_type', 'group', 'original_group', )
|
||||||
read_only_fields = ('date_created', 'date_modified',
|
read_only_fields = ('date_created', 'date_modified', 'references', 'uuid', 'cover_name', 'read_only_nullable')
|
||||||
'references', 'uuid', 'cover_name')
|
|
||||||
lookup_field = 'slug'
|
lookup_field = 'slug'
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
'body': {'help_text': 'body serializer help_text'},
|
'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, "
|
'help_text': _("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.")
|
||||||
},
|
},
|
||||||
|
'read_only_nullable': {'allow_null': True},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from rest_framework import viewsets
|
|||||||
# noinspection PyDeprecation
|
# noinspection PyDeprecation
|
||||||
from rest_framework.filters import OrderingFilter
|
from rest_framework.filters import OrderingFilter
|
||||||
from rest_framework.pagination import LimitOffsetPagination
|
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 rest_framework.response import Response
|
||||||
|
|
||||||
from articles import serializers
|
from articles import serializers
|
||||||
@@ -118,7 +118,7 @@ class ArticleViewSet(viewsets.ModelViewSet):
|
|||||||
type=openapi.TYPE_INTEGER,
|
type=openapi.TYPE_INTEGER,
|
||||||
description="this should not crash (form parameter on DELETE method)"
|
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):
|
def image(self, request, slug=None):
|
||||||
"""
|
"""
|
||||||
image method docstring
|
image method docstring
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from decimal import Decimal
|
|||||||
|
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from rest_framework import serializers
|
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
|
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):
|
class LanguageSerializer(serializers.Serializer):
|
||||||
name = serializers.ChoiceField(
|
name = serializers.ChoiceField(
|
||||||
choices=LANGUAGE_CHOICES, default='python', help_text='The name of the programming language')
|
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:
|
class Meta:
|
||||||
ref_name = None
|
ref_name = None
|
||||||
@@ -65,11 +66,13 @@ class SnippetSerializer(serializers.Serializer):
|
|||||||
)
|
)
|
||||||
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
|
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
|
||||||
code = serializers.CharField(style={'base_template': 'textarea.html'})
|
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)
|
linenos = serializers.BooleanField(required=False)
|
||||||
language = LanguageSerializer(help_text="Sample help text for language")
|
language = LanguageSerializer(help_text="Sample help text for language")
|
||||||
styles = serializers.MultipleChoiceField(choices=STYLE_CHOICES, default=['friendly'])
|
styles = serializers.MultipleChoiceField(choices=STYLE_CHOICES, default=['friendly'])
|
||||||
lines = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, allow_null=True, required=False)
|
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",
|
difficulty_factor = serializers.FloatField(help_text="this is here just to test FloatField",
|
||||||
read_only=True, default=lambda: 6.9)
|
read_only=True, default=lambda: 6.9)
|
||||||
rate_as_string = serializers.DecimalField(max_digits=6, decimal_places=3, default=Decimal('0.0'),
|
rate_as_string = serializers.DecimalField(max_digits=6, decimal_places=3, default=Decimal('0.0'),
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from djangorestframework_camel_case.parser import CamelCaseJSONParser
|
|||||||
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
|
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
|
||||||
from inflection import camelize
|
from inflection import camelize
|
||||||
from rest_framework import generics, status
|
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 import openapi
|
||||||
from drf_yasg.inspectors import SwaggerAutoSchema
|
from drf_yasg.inspectors import SwaggerAutoSchema
|
||||||
@@ -22,7 +22,7 @@ class SnippetList(generics.ListCreateAPIView):
|
|||||||
queryset = Snippet.objects.all()
|
queryset = Snippet.objects.all()
|
||||||
serializer_class = SnippetSerializer
|
serializer_class = SnippetSerializer
|
||||||
|
|
||||||
parser_classes = (FormParser, CamelCaseJSONParser,)
|
parser_classes = (FormParser, CamelCaseJSONParser, FileUploadParser)
|
||||||
renderer_classes = (CamelCaseJSONRenderer,)
|
renderer_classes = (CamelCaseJSONRenderer,)
|
||||||
swagger_schema = CamelCaseOperationIDAutoSchema
|
swagger_schema = CamelCaseOperationIDAutoSchema
|
||||||
|
|
||||||
|
|||||||
@@ -41,10 +41,11 @@ class TodoYetAnotherSerializer(serializers.ModelSerializer):
|
|||||||
|
|
||||||
class TodoTreeSerializer(serializers.ModelSerializer):
|
class TodoTreeSerializer(serializers.ModelSerializer):
|
||||||
children = serializers.ListField(child=RecursiveField(), source='children.all')
|
children = serializers.ListField(child=RecursiveField(), source='children.all')
|
||||||
|
many_children = RecursiveField(many=True, source='children')
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = TodoTree
|
model = TodoTree
|
||||||
fields = ('id', 'title', 'children')
|
fields = ('id', 'title', 'children', 'many_children')
|
||||||
|
|
||||||
|
|
||||||
class TodoRecursiveSerializer(serializers.ModelSerializer):
|
class TodoRecursiveSerializer(serializers.ModelSerializer):
|
||||||
|
|||||||
@@ -902,6 +902,11 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
format: date-time
|
format: date-time
|
||||||
readOnly: true
|
readOnly: true
|
||||||
|
read_only_nullable:
|
||||||
|
type: string
|
||||||
|
readOnly: true
|
||||||
|
minLength: 1
|
||||||
|
x-nullable: true
|
||||||
references:
|
references:
|
||||||
description: this is a really bad example
|
description: this is a really bad example
|
||||||
type: object
|
type: object
|
||||||
@@ -1023,6 +1028,7 @@ definitions:
|
|||||||
Snippet:
|
Snippet:
|
||||||
required:
|
required:
|
||||||
- code
|
- code
|
||||||
|
- tags
|
||||||
- language
|
- language
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
@@ -1057,6 +1063,13 @@ definitions:
|
|||||||
title: Code
|
title: Code
|
||||||
type: string
|
type: string
|
||||||
minLength: 1
|
minLength: 1
|
||||||
|
tags:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
minLength: 2
|
||||||
|
maxItems: 15
|
||||||
|
minItems: 3
|
||||||
linenos:
|
linenos:
|
||||||
title: Linenos
|
title: Linenos
|
||||||
type: boolean
|
type: boolean
|
||||||
@@ -1507,6 +1520,12 @@ definitions:
|
|||||||
- yaml+jinja
|
- yaml+jinja
|
||||||
- zephir
|
- zephir
|
||||||
default: python
|
default: python
|
||||||
|
readOnlyNullable:
|
||||||
|
title: Read only nullable
|
||||||
|
type: string
|
||||||
|
readOnly: true
|
||||||
|
minLength: 1
|
||||||
|
x-nullable: true
|
||||||
styles:
|
styles:
|
||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
@@ -1553,6 +1572,7 @@ definitions:
|
|||||||
items:
|
items:
|
||||||
$ref: '#/definitions/Project'
|
$ref: '#/definitions/Project'
|
||||||
readOnly: true
|
readOnly: true
|
||||||
|
maxItems: 100
|
||||||
difficultyFactor:
|
difficultyFactor:
|
||||||
title: Difficulty factor
|
title: Difficulty factor
|
||||||
description: this is here just to test FloatField
|
description: this is here just to test FloatField
|
||||||
@@ -1617,6 +1637,7 @@ definitions:
|
|||||||
required:
|
required:
|
||||||
- title
|
- title
|
||||||
- children
|
- children
|
||||||
|
- many_children
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
id:
|
id:
|
||||||
@@ -1632,6 +1653,10 @@ definitions:
|
|||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
$ref: '#/definitions/TodoTree'
|
$ref: '#/definitions/TodoTree'
|
||||||
|
many_children:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: '#/definitions/TodoTree'
|
||||||
TodoYetAnother:
|
TodoYetAnother:
|
||||||
required:
|
required:
|
||||||
- title
|
- title
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ if typing:
|
|||||||
# Following cases are not 100% correct, but it should work somehow and not crash.
|
# Following cases are not 100% correct, but it should work somehow and not crash.
|
||||||
(Union[int, float], None),
|
(Union[int, float], None),
|
||||||
(List, {'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_STRING)}),
|
(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):
|
def test_get_basic_type_info_from_hint(hint_class, expected_swagger_type_info):
|
||||||
type_info = get_basic_type_info_from_hint(hint_class)
|
type_info = get_basic_type_info_from_hint(hint_class)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from drf_yasg.openapi import ReferenceResolver
|
|||||||
|
|
||||||
def test_basic():
|
def test_basic():
|
||||||
scopes = ['s1', 's2']
|
scopes = ['s1', 's2']
|
||||||
rr = ReferenceResolver(*scopes)
|
rr = ReferenceResolver(*scopes, force_init=True)
|
||||||
assert scopes == rr.scopes == list(rr.keys()) == list(rr)
|
assert scopes == rr.scopes == list(rr.keys()) == list(rr)
|
||||||
rr.set('o1', 1, scope='s1')
|
rr.set('o1', 1, scope='s1')
|
||||||
assert rr.has('o1', scope='s1')
|
assert rr.has('o1', scope='s1')
|
||||||
@@ -25,7 +25,7 @@ def test_basic():
|
|||||||
|
|
||||||
def test_scoped():
|
def test_scoped():
|
||||||
scopes = ['s1', 's2']
|
scopes = ['s1', 's2']
|
||||||
rr = ReferenceResolver(*scopes)
|
rr = ReferenceResolver(*scopes, force_init=True)
|
||||||
r1 = rr.with_scope('s1')
|
r1 = rr.with_scope('s1')
|
||||||
r2 = rr.with_scope('s2')
|
r2 = rr.with_scope('s2')
|
||||||
with pytest.raises(AssertionError):
|
with pytest.raises(AssertionError):
|
||||||
|
|||||||
Reference in New Issue
Block a user