Compare commits

..

41 Commits

Author SHA1 Message Date
Cristi Vîjdea de3c5a77fd Add 1.9.1 changelog 2018-06-30 00:31:29 +03:00
Cristi Vîjdea 5929ff55a0 Update swagger-ui to 3.17.1 and ReDoc to 2.0.0-alpha.25 2018-06-30 00:31:16 +03:00
Cristi Vîjdea 7982f62f38 Add LICENSE file to wheel 2018-06-30 00:18:19 +03:00
Cristi Vîjdea 9fa4765121 Ignore None when passed in as response override
Closes #148
2018-06-29 23:13:36 +03:00
Jack Cushman 544d72db0a Handle duplicate urls in urlconf (#155)
Django resolves urls in order from top to bottom, and only uses the first matching URL found.
2018-06-29 22:57:37 +03:00
Cristi Vîjdea 696ec3a94a Add swagger_fake_view marker to help detect fake views in get_serializer
Cleaner fix for #154
2018-06-29 18:00:54 +03:00
Cristi Vîjdea e0aec3ff45 Test that get_serializer is not called when overriden
Views' ``get_serializer`` methods should not be called when the serializer is provided by ``request_body`` or ``responses``.

Closes #154
2018-06-29 17:41:41 +03:00
John Carter ee7b9a0734 Fix 1.9.0 changelog typo (#147) 2018-06-17 13:31:21 +03:00
Cristi Vîjdea 0697c415ed Update changelog 2018-06-16 17:04:02 +03:00
Andrew Yager 4825ec70b1 Handle swagger_extra_fields in field_to_swagger_object (#142)
* Move add_manual_fields call to make_schema_definition
* Do not call add_manual_fields twice
2018-06-16 17:02:06 +03:00
Cristi Vîjdea 54ad90415d Add 1.9.0 changelog 2018-06-16 15:55:36 +03:00
Cristi Vîjdea 1184ea8b46 Add --generator-class argument to management command
Closes #140
2018-06-16 15:54:51 +03:00
Cristi Vîjdea 6ac58b8cf7 Fix testproj duplicate operation id
Fixes #139
2018-06-16 15:41:51 +03:00
Cristi Vîjdea d627a1bc5d Handle coreapi Fields without a schema attribute
Fixes #143
2018-06-16 15:08:59 +03:00
Cristi Vîjdea 38e884b5ea Remove wrong 'count' in paginator response required fields
Fixes #141
2018-06-16 15:06:09 +03:00
Cristi Vîjdea 2ef7cfbfe3 Catch and log exceptions raised from get_serializer
Fixes #135
2018-06-01 16:21:25 +03:00
Cristi Vîjdea 58adbb8f4c Coerce read_only into a boolean 2018-06-01 15:36:37 +03:00
Cristi Vîjdea 34c7fa2b0e Update swagger-ui to 3.16.0 and ReDoc to 2.0.0-alpha.22 2018-05-31 00:35:11 +03:00
Cristi Vîjdea 6b2ce7d0f9 Update changelog and release 1.8.0 2018-05-31 00:24:48 +03:00
Cristi Vîjdea 256a052564 Add ability to set Schema fields through the serializer Meta class (#134)
* Add swagger_schema_fields attribute to serializer Meta class
* Add documentation

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

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

Closes #118
2018-05-14 19:15:14 +03:00
Cristi Vîjdea 3077195396 Update swagger-ui to 3.14.2 and ReDoc to 2.0.0-alpha.20 2018-05-14 18:59:59 +03:00
Cristi Vîjdea 94f6ca8c89 Ignore python tests in node_modules 2018-05-14 18:57:29 +03:00
Cristi Vîjdea ae5eeeb600 Ignore None return from get_operation 2018-05-14 18:36:44 +03:00
Cristi Vîjdea 23ebe2ff3e Guard against views that throw exceptions from __init__ 2018-05-12 18:14:33 +03:00
Cristi Vîjdea 713c669e28 Fix changelog syntax... 2018-05-12 14:26:23 +03:00
Cristi Vîjdea 2545ae9657 Fix SECURITY_REQUIREMENT order (again)
pain in the ass -.-
2018-05-12 14:11:37 +03:00
Cristi Vîjdea f03d9d71e9 Fix SECURITY_DEFINITIONS and SECURITY_REQUIREMENTS ordering 2018-05-12 13:54:43 +03:00
Cristi Vîjdea a993cba7aa Fix default security requirements 2018-05-12 13:35:17 +03:00
Cristi Vîjdea bfd88cbdb4 Fix security type hint 2018-05-12 13:30:57 +03:00
Cristi Vîjdea 123a05c82c Fix 1.7.1 changelog 2018-05-05 15:58:10 +03:00
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
39 changed files with 915 additions and 1986 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
- -
+1 -1
View File
@@ -36,7 +36,7 @@ You want to contribute some code? Great! Here are a few steps to get you started
$ virtualenv venv $ virtualenv venv
$ source venv/bin/activate $ source venv/bin/activate
(venv) $ pip install -e .[validation] (venv) $ pip install -e .[validation]
(venv) $ pip install -rrequirements/dev.txt "Django>=1.11.7" (venv) $ pip install -r requirements/dev.txt
#. **Make your changes and check them against the test project** #. **Make your changes and check them against the test project**
+78
View File
@@ -3,6 +3,84 @@ Changelog
######### #########
*********
**1.9.1**
*********
*Release date: Jun 30, 2018*
- **IMPROVED:** added a ``swagger_fake_view`` marker to more easily detect mock views in view methods;
``getattr(self, 'swagger_fake_view', False)`` inside a view method like ``get_serializer_class`` will tell you if the
view instnace is being used for swagger schema introspection (:issue:`154`)
- **IMPROVED:** updated ``swagger-ui`` to version 3.17.1
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.25
- **FIXED:** fixed wrong handling of duplicate urls in urlconf (:pr:`155`)
- **FIXED:** fixed crash when passing ``None`` as a response override (:issue:`148`)
*********
**1.9.0**
*********
*Release date: Jun 16, 2018*
- **ADDED:** added ``DEFAULT_GENERATOR_CLASS`` setting and ``--generator-class`` argument to the ``generate_swagger``
management command (:issue:`140`)
- **FIXED:** fixed wrongly required ``'count'`` response field on ``CursorPagination`` (:issue:`141`)
- **FIXED:** fixed some cases where ``swagger_extra_fields`` would not be handlded (:pr:`142`)
- **FIXED:** fixed crash when encountering ``coreapi.Fields``\ s without a ``schema`` (:issue:`143`)
*********
**1.8.0**
*********
*Release date: Jun 01, 2018*
- **ADDED:** added a :ref:`swagger_schema_fields <swagger_schema_fields>` field on serializer ``Meta`` classes for
customizing schema generation (:issue:`132`, :pr:`134`)
- **FIXED:** error responses from schema views are now rendered with ``JSONRenderer`` instead of throwing
confusing errors (:pr:`130`, :issue:`58`)
- **FIXED:** ``readOnly`` schema fields will now no longer be marked as ``required`` (:pr:`133`)
*********
**1.7.4**
*********
*Release date: May 14, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.14.2
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.20
- **FIXED:** ignore ``None`` return from ``get_operation`` to avoid empty ``Path`` objects in output
- **FIXED:** request body is now allowed on ``DELETE`` endpoints (:issue:`118`)
*********
**1.7.3**
*********
*Release date: May 12, 2018*
- **FIXED:** views whose ``__init__`` methods throw exceptions will now be ignored during endpoint enumeration
*********
**1.7.2**
*********
*Release date: May 12, 2018*
- **FIXED:** fixed generation of default ``SECURITY_REQUIREMENTS`` to match documented behaviour
- **FIXED:** ordering of ``SECURITY_REQUIREMENTS`` and ``SECURITY_DEFINITIONS`` is now stable
*********
**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
- **IMPROVED:** set ``min_length=1`` when ``allow_blank=False`` (:pr:`112`, thanks to :ghuser:`elnappo`)
- **FIXED:** made documentation ordering of ``SwaggerDict`` extra attributes stable
********* *********
**1.7.0** **1.7.0**
********* *********
+7 -1
View File
@@ -169,13 +169,19 @@ You can define some per-serializer options by adding a ``Meta`` class to your se
class Meta: class Meta:
... options here ... ... options here ...
Currently, the only option you can add here is .. _swagger_schema_fields:
The available options are:
* ``ref_name`` - a string which will be used as the model definition name for this serializer class; setting it to * ``ref_name`` - a string which will be used as the model definition name for this serializer class; setting it to
``None`` will force the serializer to be generated as an inline model everywhere it is used. If two serializers ``None`` will force the serializer to be generated as an inline model everywhere it is used. If two serializers
have the same ``ref_name``, both their usages will be replaced with a reference to the same definition. have the same ``ref_name``, both their usages will be replaced with a reference to the same definition.
If this option is not specified, all serializers have an implicit name derived from their class name, minus any If this option is not specified, all serializers have an implicit name derived from their class name, minus any
``Serializer`` suffix (e.g. ``UserSerializer`` -> ``User``, ``SerializerWithSuffix`` -> ``SerializerWithSuffix``) ``Serializer`` suffix (e.g. ``UserSerializer`` -> ``User``, ``SerializerWithSuffix`` -> ``SerializerWithSuffix``)
* ``swagger_schema_fields`` - a dictionary mapping :class:`.Schema` field names to values. These attributes
will be set on the :class:`.Schema` object generated from the ``Serializer``. Field names must be python values,
which are converted to Swagger ``Schema`` attribute names according to :func:`.make_swagger_name`.
Attribute names and values must conform to the `OpenAPI 2.0 specification <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject>`_.
************************* *************************
+9
View File
@@ -174,6 +174,15 @@ in a few ways:
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`, to prevent ``get_serializer`` from being called on :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`, to prevent ``get_serializer`` from being called on
the view the view
* :ref:`exclude your endpoint from introspection <custom-spec-excluding-endpoints>` * :ref:`exclude your endpoint from introspection <custom-spec-excluding-endpoints>`
* use the ``swagger_fake_view`` marker to detect requests generated by ``drf-yasg``:
.. code-block:: python
def get_serializer_class(self):
if getattr(self, 'swagger_fake_view', False):
return TodoTreeSerializer
raise NotImplementedError("must not call this")
.. _SCRIPT_NAME: https://www.python.org/dev/peps/pep-0333/#environ-variables .. _SCRIPT_NAME: https://www.python.org/dev/peps/pep-0333/#environ-variables
.. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name .. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name
+1 -1
View File
@@ -39,7 +39,7 @@ Security requirements
The second step is specifying, for each endpoint, which authentication mechanism can be used for interacting with it. The second step is specifying, for each endpoint, which authentication mechanism can be used for interacting with it.
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object for details. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object for details.
By default, a top-level `security` that accepts all the declared security definitions is generated. By default, a top-level `security` that accepts any one of the declared security definitions is generated.
For the example above, that would be :code:`[{'Basic': []}, {'Bearer': []}]`. This can be overriden using the For the example above, that would be :code:`[{'Basic': []}, {'Bearer': []}]`. This can be overriden using the
:ref:`SECURITY_REQUIREMENTS <security-definitions-settings>` setting. :ref:`SECURITY_REQUIREMENTS <security-definitions-settings>` setting.
+18 -1
View File
@@ -43,6 +43,14 @@ The possible settings and their default values are as follows:
Default classes Default classes
=============== ===============
DEFAULT_GENERATOR_CLASS
-------------------------
:class:`~.generators.OpenAPISchemaGenerator` subclass that will be used by default for generating the final
:class:`.Schema` object. Can be overriden by the ``generator_class`` argument to :func:`.get_schema_view`.
**Default**: :class:`drf_yasg.generators.OpenAPISchemaGenerator`
DEFAULT_AUTO_SCHEMA_CLASS DEFAULT_AUTO_SCHEMA_CLASS
------------------------- -------------------------
@@ -102,7 +110,7 @@ DEFAULT_INFO
------------ ------------
An import string to an :class:`.openapi.Info` object. This will be used when running the ``generate_swagger`` An import string to an :class:`.openapi.Info` object. This will be used when running the ``generate_swagger``
management command, or if no ``info`` argument is passed to ``get_schema_view``. management command, or if no ``info`` argument is passed to :func:`.get_schema_view`.
**Default**: :python:`None` **Default**: :python:`None`
@@ -255,6 +263,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
+329 -1807
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,8 +1,8 @@
{ {
"name": "drf-yasg", "name": "drf-yasg",
"dependencies": { "dependencies": {
"redoc": "^2.0.0-alpha.17", "redoc": "^2.0.0-alpha.25",
"swagger-ui-dist": "^3.13.6" "swagger-ui-dist": "^3.17.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
+3
View File
@@ -1,2 +1,5 @@
[bdist_wheel] [bdist_wheel]
universal = 1 universal = 1
[metadata]
license_file = LICENSE.rst
+3
View File
@@ -2,6 +2,7 @@ from django.conf import settings
from rest_framework.settings import perform_import from rest_framework.settings import perform_import
SWAGGER_DEFAULTS = { SWAGGER_DEFAULTS = {
'DEFAULT_GENERATOR_CLASS': 'drf_yasg.generators.OpenAPISchemaGenerator',
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.inspectors.SwaggerAutoSchema', 'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.inspectors.SwaggerAutoSchema',
'DEFAULT_FIELD_INSPECTORS': [ 'DEFAULT_FIELD_INSPECTORS': [
@@ -45,6 +46,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': [
@@ -67,6 +69,7 @@ REDOC_DEFAULTS = {
} }
IMPORT_STRINGS = [ IMPORT_STRINGS = [
'DEFAULT_GENERATOR_CLASS',
'DEFAULT_AUTO_SCHEMA_CLASS', 'DEFAULT_AUTO_SCHEMA_CLASS',
'DEFAULT_FIELD_INSPECTORS', 'DEFAULT_FIELD_INSPECTORS',
'DEFAULT_FILTER_INSPECTORS', 'DEFAULT_FILTER_INSPECTORS',
+38 -13
View File
@@ -72,7 +72,7 @@ class EndpointEnumerator(_EndpointEnumerator):
return path return path
def get_api_endpoints(self, patterns=None, prefix='', app_name=None, namespace=None): def get_api_endpoints(self, patterns=None, prefix='', app_name=None, namespace=None, previously_seen_endpoints=None):
""" """
Return a list of all available API endpoints by inspecting the URL conf. Return a list of all available API endpoints by inspecting the URL conf.
@@ -82,25 +82,38 @@ class EndpointEnumerator(_EndpointEnumerator):
patterns = self.patterns patterns = self.patterns
api_endpoints = [] api_endpoints = []
if previously_seen_endpoints is None:
previously_seen_endpoints = set()
for pattern in patterns: for pattern in patterns:
path_regex = prefix + get_original_route(pattern) path_regex = prefix + get_original_route(pattern)
if isinstance(pattern, URLPattern): if isinstance(pattern, URLPattern):
path = self.get_path_from_regex(path_regex) try:
callback = pattern.callback path = self.get_path_from_regex(path_regex)
url_name = pattern.name callback = pattern.callback
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name): url_name = pattern.name
path = self.replace_version(path, callback) if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
for method in self.get_allowed_methods(callback): path = self.replace_version(path, callback)
endpoint = (path, method, callback)
api_endpoints.append(endpoint) # avoid adding endpoints that have already been seen,
# as Django resolves urls in top-down order
if path in previously_seen_endpoints:
continue
previously_seen_endpoints.add(path)
for method in self.get_allowed_methods(callback):
endpoint = (path, method, callback)
api_endpoints.append(endpoint)
except Exception: # pragma: no cover
logger.warning('failed to enumerate view', exc_info=True)
elif isinstance(pattern, URLResolver): elif isinstance(pattern, URLResolver):
nested_endpoints = self.get_api_endpoints( nested_endpoints = self.get_api_endpoints(
patterns=pattern.url_patterns, patterns=pattern.url_patterns,
prefix=path_regex, prefix=path_regex,
app_name="%s:%s" % (app_name, pattern.app_name) if app_name else pattern.app_name, app_name="%s:%s" % (app_name, pattern.app_name) if app_name else pattern.app_name,
namespace="%s:%s" % (namespace, pattern.namespace) if namespace else pattern.namespace namespace="%s:%s" % (namespace, pattern.namespace) if namespace else pattern.namespace,
previously_seen_endpoints=previously_seen_endpoints
) )
api_endpoints.extend(nested_endpoints) api_endpoints.extend(nested_endpoints)
else: else:
@@ -204,9 +217,15 @@ class OpenAPISchemaGenerator(object):
paths, prefix = self.get_paths(endpoints, components, request, public) paths, prefix = self.get_paths(endpoints, components, request, public)
security_definitions = swagger_settings.SECURITY_DEFINITIONS security_definitions = swagger_settings.SECURITY_DEFINITIONS
if security_definitions is not None:
security_definitions = OrderedDict(sorted([(key, OrderedDict(sorted(sd.items())))
for key, sd in swagger_settings.SECURITY_DEFINITIONS.items()]))
security_requirements = swagger_settings.SECURITY_REQUIREMENTS security_requirements = swagger_settings.SECURITY_REQUIREMENTS
if security_requirements is None: if security_requirements is None:
security_requirements = [{security_scheme: [] for security_scheme in swagger_settings.SECURITY_DEFINITIONS}] security_requirements = [{security_scheme: []} for security_scheme in swagger_settings.SECURITY_DEFINITIONS]
security_requirements = sorted(security_requirements, key=lambda od: list(sorted(od)))
security_requirements = [OrderedDict(sorted(sr.items())) for sr in security_requirements]
url = self.url url = self.url
if url is None and request is not None: if url is None and request is not None:
@@ -234,6 +253,8 @@ class OpenAPISchemaGenerator(object):
view_method = getattr(view, method, None) view_method = getattr(view, method, None)
if view_method is not None: # pragma: no cover if view_method is not None: # pragma: no cover
setattr(view_method.__func__, '_swagger_auto_schema', overrides) setattr(view_method.__func__, '_swagger_auto_schema', overrides)
setattr(view, 'swagger_fake_view', True)
return view return view
def get_endpoints(self, request): def get_endpoints(self, request):
@@ -315,7 +336,9 @@ class OpenAPISchemaGenerator(object):
if not public and not self._gen.has_view_permissions(path, method, view): if not public and not self._gen.has_view_permissions(path, method, view):
continue continue
operations[method.lower()] = self.get_operation(view, path, prefix, method, components, request) operation = self.get_operation(view, path, prefix, method, components, request)
if operation is not None:
operations[method.lower()] = operation
if operations: if operations:
# since the common prefix is used as the API basePath, it must be stripped # since the common prefix is used as the API basePath, it must be stripped
@@ -356,6 +379,9 @@ class OpenAPISchemaGenerator(object):
view_inspector = view_inspector_cls(view, path, method, components, request, overrides) view_inspector = view_inspector_cls(view, path, method, components, request, overrides)
operation = view_inspector.get_operation(operation_keys) operation = view_inspector.get_operation(operation_keys)
if operation is None:
return None
if 'consumes' in operation and set(operation.consumes) == set(self.consumes): if 'consumes' in operation and set(operation.consumes) == set(self.consumes):
del operation.consumes del operation.consumes
if 'produces' in operation and set(operation.produces) == set(self.produces): if 'produces' in operation and set(operation.produces) == set(self.produces):
@@ -401,7 +427,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)
+4 -1
View File
@@ -276,7 +276,10 @@ class SerializerInspector(FieldInspector):
class ViewInspector(BaseInspector): class ViewInspector(BaseInspector):
body_methods = ('PUT', 'PATCH', 'POST') #: methods that are allowed to have a request body body_methods = ('PUT', 'PATCH', 'POST', 'DELETE') #: methods that are allowed to have a request body
#: methods that are assumed to require a request body determined by the view's ``serializer_class``
implicit_body_methods = ('PUT', 'PATCH', 'POST')
# real values set in __init__ to prevent import errors # real values set in __init__ to prevent import errors
field_inspectors = [] #: field_inspectors = [] #:
+45 -6
View File
@@ -22,12 +22,36 @@ class InlineSerializerInspector(SerializerInspector):
#: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section #: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section
use_definitions = False use_definitions = False
def add_manual_fields(self, serializer, schema):
"""Set fields from the ``swagger_schem_fields`` attribute on the serializer's Meta class. This method is called
only for serializers that are converted into ``openapi.Schema`` objects.
:param serializer: serializer instance
:param openapi.Schema schema: the schema object to be modified in-place
"""
serializer_meta = getattr(serializer, 'Meta', None)
swagger_schema_fields = getattr(serializer_meta, 'swagger_schema_fields', {})
if swagger_schema_fields:
for attr, val in swagger_schema_fields.items():
setattr(schema, attr, val)
def get_schema(self, serializer): def get_schema(self, serializer):
return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions) return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions)
def add_manual_parameters(self, serializer, parameters):
"""Add/replace parameters from the given list of automatically generated request parameters. This method
is called only when the serializer is converted into a list of parameters for use in a form data request.
:param serializer: serializer instance
:param list[openapi.Parameter] parameters: genereated parameters
:return: modified parameters
:rtype: list[openapi.Parameter]
"""
return parameters
def get_request_parameters(self, serializer, in_): def get_request_parameters(self, serializer, in_):
fields = getattr(serializer, 'fields', {}) fields = getattr(serializer, 'fields', {})
return [ parameters = [
self.probe_field_inspectors( self.probe_field_inspectors(
value, openapi.Parameter, self.use_definitions, value, openapi.Parameter, self.use_definitions,
name=self.get_parameter_name(key), in_=in_ name=self.get_parameter_name(key), in_=in_
@@ -36,12 +60,17 @@ class InlineSerializerInspector(SerializerInspector):
in fields.items() in fields.items()
] ]
return self.add_manual_parameters(serializer, parameters)
def get_property_name(self, field_name): def get_property_name(self, field_name):
return field_name return field_name
def get_parameter_name(self, field_name): def get_parameter_name(self, field_name):
return field_name return field_name
def get_serializer_ref_name(self, serializer):
return get_serializer_ref_name(serializer)
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs): def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs) SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
@@ -55,7 +84,7 @@ class InlineSerializerInspector(SerializerInspector):
if swagger_object_type != openapi.Schema: if swagger_object_type != openapi.Schema:
raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__) raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__)
ref_name = get_serializer_ref_name(field) ref_name = self.get_serializer_ref_name(field)
def make_schema_definition(): def make_schema_definition():
properties = OrderedDict() properties = OrderedDict()
@@ -63,14 +92,16 @@ class InlineSerializerInspector(SerializerInspector):
for property_name, child in field.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': bool(child.read_only) or None
} }
prop_kwargs = filter_none(prop_kwargs) prop_kwargs = filter_none(prop_kwargs)
properties[property_name] = self.probe_field_inspectors( child_schema = self.probe_field_inspectors(
child, ChildSwaggerType, use_references, **prop_kwargs child, ChildSwaggerType, use_references, **prop_kwargs
) )
if child.required: properties[property_name] = child_schema
if child.required and not getattr(child_schema, 'read_only', False):
required.append(property_name) required.append(property_name)
result = SwaggerType( result = SwaggerType(
@@ -83,6 +114,10 @@ class InlineSerializerInspector(SerializerInspector):
# but is visually displayed like the model name, which is confusing # but is visually displayed like the model name, which is confusing
# 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
# Provide an option to add manual paremeters to a schema
# for example, to add examples
self.add_manual_fields(field, result)
return result return result
if not ref_name or not use_references: if not ref_name or not use_references:
@@ -281,6 +316,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()))
@@ -523,7 +562,7 @@ else:
try: try:
from rest_framework_recursive.fields import RecursiveField from rest_framework_recursive.fields import RecursiveField
except ImportError: except ImportError: # pragma: no cover
class RecursiveFieldInspector(FieldInspector): class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)""" """Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
pass pass
+5 -2
View File
@@ -48,7 +48,7 @@ class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
in_=location_to_in[field.location], in_=location_to_in[field.location],
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING), type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
required=field.required, required=field.required,
description=field.schema.description, description=field.schema.description if field.schema else None,
) )
@@ -70,7 +70,10 @@ class DjangoRestResponsePagination(PaginatorInspector):
('previous', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)), ('previous', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)),
('results', response_schema), ('results', response_schema),
)), )),
required=['count', 'results'] required=['results']
) )
if has_count:
paged_schema.required.insert(0, 'count')
return paged_schema return paged_schema
+16 -3
View File
@@ -1,3 +1,4 @@
import logging
from collections import OrderedDict from collections import OrderedDict
from rest_framework.request import is_form_media_type from rest_framework.request import is_form_media_type
@@ -12,6 +13,8 @@ from ..utils import (
) )
from .base import ViewInspector from .base import ViewInspector
log = logging.getLogger(__name__)
class SwaggerAutoSchema(ViewInspector): class SwaggerAutoSchema(ViewInspector):
def __init__(self, view, path, method, components, request, overrides): def __init__(self, view, path, method, components, request, overrides):
@@ -83,7 +86,12 @@ class SwaggerAutoSchema(ViewInspector):
""" """
if not hasattr(self.view, 'get_serializer'): if not hasattr(self.view, 'get_serializer'):
return None return None
return self.view.get_serializer() try:
return self.view.get_serializer()
except Exception:
log.warning("view's get_serializer raised exception (%s %s %s)",
self.method, self.path, type(self.view).__name__, exc_info=True)
return None
def get_request_serializer(self): def get_request_serializer(self):
"""Return the request serializer (used for parsing the request payload) for this endpoint. """Return the request serializer (used for parsing the request payload) for this endpoint.
@@ -101,7 +109,7 @@ class SwaggerAutoSchema(ViewInspector):
if isinstance(body_override, openapi.Schema.OR_REF): if isinstance(body_override, openapi.Schema.OR_REF):
return body_override return body_override
return force_serializer_instance(body_override) return force_serializer_instance(body_override)
elif self.method in self.body_methods: elif self.method in self.implicit_body_methods:
return self.get_view_serializer() return self.get_view_serializer()
return None return None
@@ -144,8 +152,11 @@ class SwaggerAutoSchema(ViewInspector):
raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body") raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body")
if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover
if any(param.in_ == openapi.IN_BODY for param in parameters.values()): if any(param.in_ == openapi.IN_BODY for param in parameters.values()):
raise SwaggerGenerationError("cannot add form parameters when the request has a request schema; " raise SwaggerGenerationError("cannot add form parameters when the request has a request body; "
"did you forget to set an appropriate parser class on the view?") "did you forget to set an appropriate parser class on the view?")
if self.method not in self.body_methods:
raise SwaggerGenerationError("form parameters can only be applied to (" + ','.join(self.body_methods) +
") HTTP methods")
parameters.update(param_list_to_odict(manual_parameters)) parameters.update(param_list_to_odict(manual_parameters))
return list(parameters.values()) return list(parameters.values())
@@ -219,6 +230,8 @@ class SwaggerAutoSchema(ViewInspector):
response = openapi.Response( response = openapi.Response(
description=serializer description=serializer
) )
elif not serializer:
continue
elif isinstance(serializer, openapi.Response): elif isinstance(serializer, openapi.Response):
response = serializer response = serializer
if hasattr(response, 'schema') and not isinstance(response.schema, openapi.Schema.OR_REF): if hasattr(response, 'schema') and not isinstance(response.schema, openapi.Schema.OR_REF):
@@ -2,6 +2,7 @@ import json
import logging import logging
import os import os
from collections import OrderedDict from collections import OrderedDict
from importlib import import_module
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
@@ -12,7 +13,15 @@ from rest_framework.views import APIView
from ... import openapi from ... import openapi
from ...app_settings import swagger_settings from ...app_settings import swagger_settings
from ...codecs import OpenAPICodecJson, OpenAPICodecYaml from ...codecs import OpenAPICodecJson, OpenAPICodecYaml
from ...generators import OpenAPISchemaGenerator
def import_class(import_string):
if not import_string:
return None
module_path, class_name = import_string.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
class Command(BaseCommand): class Command(BaseCommand):
@@ -64,6 +73,11 @@ class Command(BaseCommand):
'OpenAPISchemaGenerator.get_schema().\n' 'OpenAPISchemaGenerator.get_schema().\n'
'This option implies --mock-request.' 'This option implies --mock-request.'
) )
parser.add_argument(
'-g', '--generator-class', dest='generator_class_name',
default='',
help='Import string pointing to an OpenAPISchemaGenerator subclass to use for schema generation.'
)
def write_schema(self, schema, stream, format): def write_schema(self, schema, stream, format):
if format == 'json': if format == 'json':
@@ -89,7 +103,8 @@ class Command(BaseCommand):
request = APIView().initialize_request(request) request = APIView().initialize_request(request)
return request return request
def handle(self, output_file, overwrite, format, api_url, mock, user, private, *args, **options): def handle(self, output_file, overwrite, format, api_url, mock, user, private, generator_class_name,
*args, **kwargs):
# disable logs of WARNING and below # disable logs of WARNING and below
logging.disable(logging.WARNING) logging.disable(logging.WARNING)
@@ -117,7 +132,8 @@ class Command(BaseCommand):
request = self.get_mock_request(api_url, format, user) if mock else None request = self.get_mock_request(api_url, format, user) if mock else None
generator = OpenAPISchemaGenerator( generator_class = import_class(generator_class_name) or swagger_settings.DEFAULT_GENERATOR_CLASS
generator = generator_class(
info=info, info=info,
url=api_url url=api_url
) )
+2 -2
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
@@ -221,7 +221,7 @@ class Swagger(SwaggerDict):
:param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi :param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi
SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable
:param str _version: version string to override Info :param str _version: version string to override Info
:param list[dict] security_definitions: list of supported authentication mechanisms :param dict[str,dict[str,str]] security_definitions: list of supported authentication mechanisms
:param list[dict] security: authentication mechanisms accepted by default; can be overriden in Operation :param list[dict] security: authentication mechanisms accepted by default; can be overriden in Operation
:param list[str] consumes: consumed MIME types; can be overriden in Operation :param list[str] consumes: consumed MIME types; can be overriden in Operation
:param list[str] produces: produced MIME types; can be overriden in Operation :param list[str] produces: produced MIME types; can be overriden in Operation
+10 -3
View File
@@ -1,5 +1,5 @@
from django.shortcuts import render, resolve_url from django.shortcuts import render, resolve_url
from rest_framework.renderers import BaseRenderer, TemplateHTMLRenderer from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer
from rest_framework.utils import json from rest_framework.utils import json
from drf_yasg.openapi import Swagger from drf_yasg.openapi import Swagger
@@ -10,7 +10,7 @@ from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
class _SpecRenderer(BaseRenderer): class _SpecRenderer(BaseRenderer):
"""Base class for text renderers. Handles encoding and validation.""" """Base class for text renderers. Handles encoding and validation."""
charset = None charset = 'utf-8'
validators = [] validators = []
codec_class = None codec_class = None
@@ -22,6 +22,12 @@ class _SpecRenderer(BaseRenderer):
def render(self, data, media_type=None, renderer_context=None): def render(self, data, media_type=None, renderer_context=None):
assert self.codec_class, "must override codec_class" assert self.codec_class, "must override codec_class"
codec = self.codec_class(self.validators) codec = self.codec_class(self.validators)
if not isinstance(data, Swagger): # pragma: no cover
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58
return JSONRenderer().render(data, media_type, renderer_context)
return codec.encode(data) return codec.encode(data)
@@ -53,7 +59,7 @@ class _UIRenderer(BaseRenderer):
template = '' template = ''
def render(self, swagger, accepted_media_type=None, renderer_context=None): def render(self, swagger, accepted_media_type=None, renderer_context=None):
if not isinstance(swagger, Swagger): if not isinstance(swagger, Swagger): # pragma: no cover
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response`` # if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it # in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58 # see https://github.com/axnsan12/drf-yasg/issues/58
@@ -93,6 +99,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
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -1
View File
@@ -66,7 +66,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
:param str operation_id: operation ID override; the operation ID must be unique accross the whole API :param str operation_id: operation ID override; the operation ID must be unique accross the whole API
:param str operation_description: operation description override :param str operation_description: operation description override
:param str security: security requirements override; used to specify which authetication mechanism :param list[dict] security: security requirements override; used to specify which authetication mechanism
is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
authentication schemes), and ``None`` will inherit the top-level secuirty requirements authentication schemes), and ``None`` will inherit the top-level secuirty requirements
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses :param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
@@ -76,6 +76,8 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
* if a plain string is given as value, a :class:`.Response` with no body and that string as its description * if a plain string is given as value, a :class:`.Response` with no body and that string as its description
will be generated will be generated
* if ``None`` is given as a value, the response is ignored; this is mainly useful for disabling default
2xx responses, i.e. ``responses={200: None, 302: 'something'}``
* if a :class:`.Schema`, :class:`.SchemaRef` is given, a :class:`.Response` with the schema as its body and * if a :class:`.Schema`, :class:`.SchemaRef` is given, a :class:`.Response` with the schema as its body and
an empty description will be generated an empty description will be generated
* a ``Serializer`` class or instance will be converted into a :class:`.Schema` and treated as above * a ``Serializer`` class or instance will be converted into a :class:`.Schema` and treated as above
+1 -2
View File
@@ -11,7 +11,6 @@ from rest_framework.settings import api_settings
from rest_framework.views import APIView from rest_framework.views import APIView
from .app_settings import swagger_settings from .app_settings import swagger_settings
from .generators import OpenAPISchemaGenerator
from .renderers import OpenAPIRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer from .renderers import OpenAPIRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer) SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
@@ -46,7 +45,7 @@ def deferred_never_cache(view_func):
def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None, def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None,
generator_class=OpenAPISchemaGenerator, generator_class=swagger_settings.DEFAULT_GENERATOR_CLASS,
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES, authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES): permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
"""Create a SchemaView class with default renderers and generators. """Create a SchemaView class with default renderers and generators.
+1 -1
View File
@@ -11,7 +11,7 @@ class ArticleSerializer(serializers.ModelSerializer):
read_only=True, read_only=True,
) )
uuid = serializers.UUIDField(help_text="should articles have UUIDs?", read_only=True) uuid = serializers.UUIDField(help_text="should articles have UUIDs?", read_only=True)
cover_name = serializers.FileField(use_url=False, source='cover', read_only=True) cover_name = serializers.FileField(use_url=False, source='cover', required=True)
group = serializers.SlugRelatedField(slug_field='uuid', queryset=ArticleGroup.objects.all()) group = serializers.SlugRelatedField(slug_field='uuid', queryset=ArticleGroup.objects.all())
original_group = serializers.SlugRelatedField(slug_field='uuid', read_only=True) original_group = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
+35 -12
View File
@@ -33,6 +33,21 @@ class SnippetList(generics.ListCreateAPIView):
"""post method docstring""" """post method docstring"""
return super(SnippetList, self).post(request, *args, **kwargs) return super(SnippetList, self).post(request, *args, **kwargs)
@swagger_auto_schema(
operation_id='snippets_delete_bulk',
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'body': openapi.Schema(
type=openapi.TYPE_STRING,
description='this should not crash (request body on DELETE method)'
)
}
),
)
def delete(self, *args, **kwargs):
pass
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
""" """
@@ -56,18 +71,26 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
"""patch method docstring""" """patch method docstring"""
return super(SnippetDetail, self).patch(request, *args, **kwargs) return super(SnippetDetail, self).patch(request, *args, **kwargs)
@swagger_auto_schema(manual_parameters=[ @swagger_auto_schema(
openapi.Parameter( manual_parameters=[
name='id', in_=openapi.IN_PATH, openapi.Parameter(
type=openapi.TYPE_INTEGER, name='id', in_=openapi.IN_PATH,
description="path parameter override", type=openapi.TYPE_INTEGER,
required=True description="path parameter override",
), required=True
], responses={ ),
status.HTTP_204_NO_CONTENT: openapi.Response( openapi.Parameter(
description="This should not crash" name='delete_form_param', in_=openapi.IN_FORM,
) type=openapi.TYPE_INTEGER,
}) description="this should not crash (form parameter on DELETE method)"
),
],
responses={
status.HTTP_204_NO_CONTENT: openapi.Response(
description="this should not crash (response object with no schema)"
)
}
)
def delete(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs):
"""delete method docstring""" """delete method docstring"""
return super(SnippetDetail, self).patch(request, *args, **kwargs) return super(SnippetDetail, self).patch(request, *args, **kwargs)
+12 -1
View File
@@ -94,7 +94,18 @@ SWAGGER_SETTINGS = {
'LOGIN_URL': '/admin/login', 'LOGIN_URL': '/admin/login',
'LOGOUT_URL': '/admin/logout', 'LOGOUT_URL': '/admin/logout',
'DEFAULT_INFO': 'testproj.urls.swagger_info' 'DEFAULT_INFO': 'testproj.urls.swagger_info',
'SECURITY_DEFINITIONS': {
'Basic': {
'type': 'basic'
},
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
}
} }
# Internationalization # Internationalization
+11
View File
@@ -1,3 +1,5 @@
from collections import OrderedDict
from django.utils import timezone from django.utils import timezone
from rest_framework import serializers from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField from rest_framework_recursive.fields import RecursiveField
@@ -26,6 +28,15 @@ class TodoYetAnotherSerializer(serializers.ModelSerializer):
model = TodoYetAnother model = TodoYetAnother
fields = ('title', 'todo') fields = ('title', 'todo')
depth = 2 depth = 2
swagger_schema_fields = {
'example': OrderedDict([
('title', 'parent'),
('todo', OrderedDict([
('title', 'child'),
('todo', None),
])),
])
}
class TodoTreeSerializer(serializers.ModelSerializer): class TodoTreeSerializer(serializers.ModelSerializer):
+1 -1
View File
@@ -13,6 +13,6 @@ 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+)/yetanothers/(?P<yetanother_id>\d+)/$',
views.NestedTodoView.as_view(), ), views.NestedTodoView.as_view(), ),
] ]
+40 -2
View File
@@ -1,6 +1,8 @@
from rest_framework import viewsets from rest_framework import viewsets
from rest_framework.generics import RetrieveAPIView from rest_framework.generics import RetrieveAPIView
from drf_yasg.utils import swagger_auto_schema
from .models import Todo, TodoAnother, TodoTree, TodoYetAnother from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
from .serializer import ( from .serializer import (
TodoAnotherSerializer, TodoRecursiveSerializer, TodoSerializer, TodoTreeSerializer, TodoYetAnotherSerializer TodoAnotherSerializer, TodoRecursiveSerializer, TodoSerializer, TodoTreeSerializer, TodoYetAnotherSerializer
@@ -31,9 +33,45 @@ class NestedTodoView(RetrieveAPIView):
class TodoTreeView(viewsets.ReadOnlyModelViewSet): class TodoTreeView(viewsets.ReadOnlyModelViewSet):
queryset = TodoTree.objects.all() queryset = TodoTree.objects.all()
serializer_class = TodoTreeSerializer
def get_serializer_class(self):
if getattr(self, 'swagger_fake_view', False):
return TodoTreeSerializer
raise NotImplementedError("must not call this")
class TodoRecursiveView(viewsets.ModelViewSet): class TodoRecursiveView(viewsets.ModelViewSet):
queryset = TodoTree.objects.all() queryset = TodoTree.objects.all()
serializer_class = TodoRecursiveSerializer
def get_serializer(self, *args, **kwargs):
raise NotImplementedError("must not call this")
def get_serializer_class(self):
raise NotImplementedError("must not call this")
def get_serializer_context(self):
raise NotImplementedError("must not call this")
@swagger_auto_schema(request_body=TodoRecursiveSerializer)
def create(self, request, *args, **kwargs):
return super(TodoRecursiveView, self).create(request, *args, **kwargs)
@swagger_auto_schema(responses={200: None, 302: 'Redirect somewhere'})
def retrieve(self, request, *args, **kwargs):
return super(TodoRecursiveView, self).retrieve(request, *args, **kwargs)
@swagger_auto_schema(request_body=TodoRecursiveSerializer)
def update(self, request, *args, **kwargs):
return super(TodoRecursiveView, self).update(request, *args, **kwargs)
@swagger_auto_schema(request_body=TodoRecursiveSerializer)
def partial_update(self, request, *args, **kwargs):
return super(TodoRecursiveView, self).update(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
return super(TodoRecursiveView, self).destroy(request, *args, **kwargs)
@swagger_auto_schema(responses={200: TodoRecursiveSerializer(many=True)})
def list(self, request, *args, **kwargs):
return super(TodoRecursiveView, self).list(request, *args, **kwargs)
+59 -9
View File
@@ -21,10 +21,15 @@ consumes:
produces: produces:
- application/json - application/json
securityDefinitions: securityDefinitions:
basic: Basic:
type: basic type: basic
Bearer:
in: header
name: Authorization
type: apiKey
security: security:
- basic: [] - Basic: []
- Bearer: []
paths: paths:
/articles/: /articles/:
get: get:
@@ -202,6 +207,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
@@ -382,6 +388,24 @@ paths:
$ref: '#/definitions/Snippet' $ref: '#/definitions/Snippet'
tags: tags:
- snippets - snippets
delete:
operationId: snippetsDeleteBulk
description: SnippetList classdoc
parameters:
- name: data
in: body
required: true
schema:
type: object
properties:
body:
description: this should not crash (request body on DELETE method)
type: string
responses:
'204':
description: ''
tags:
- snippets
parameters: [] parameters: []
/snippets/{id}/: /snippets/{id}/:
get: get:
@@ -436,9 +460,13 @@ paths:
description: path parameter override description: path parameter override
required: true required: true
type: integer type: integer
- name: delete_form_param
in: formData
description: this should not crash (form parameter on DELETE method)
type: integer
responses: responses:
'204': '204':
description: This should not crash description: this should not crash (response object with no schema)
tags: tags:
- snippets - snippets
parameters: parameters:
@@ -532,10 +560,8 @@ paths:
description: '' description: ''
parameters: [] parameters: []
responses: responses:
'200': '302':
description: '' description: Redirect somewhere
schema:
$ref: '#/definitions/TodoRecursive'
tags: tags:
- todo - todo
put: put:
@@ -669,9 +695,9 @@ paths:
description: A unique integer value identifying this todo. description: A unique integer value identifying this todo.
required: true required: true
type: integer type: integer
/todo/{todo_id}/yetanother/{yetanother_id}/: /todo/{todo_id}/yetanothers/{yetanother_id}/:
get: get:
operationId: todo_yetanother_read operationId: todo_yetanothers_read
description: '' description: ''
parameters: [] parameters: []
responses: responses:
@@ -700,6 +726,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!
@@ -800,6 +827,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.
@@ -809,6 +837,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
@@ -830,6 +859,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?
@@ -872,10 +902,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
@@ -897,10 +929,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
@@ -922,6 +956,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
@@ -930,6 +965,7 @@ definitions:
code: code:
title: Code title: Code
type: string type: string
minLength: 1
linenos: linenos:
title: Linenos title: Linenos
type: boolean type: boolean
@@ -1448,6 +1484,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
TodoAnother: TodoAnother:
required: required:
- title - title
@@ -1458,6 +1495,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
todo: todo:
$ref: '#/definitions/Todo' $ref: '#/definitions/Todo'
TodoRecursive: TodoRecursive:
@@ -1473,6 +1511,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
parent: parent:
$ref: '#/definitions/TodoRecursive' $ref: '#/definitions/TodoRecursive'
parent_id: parent_id:
@@ -1492,6 +1531,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
children: children:
type: array type: array
items: items:
@@ -1505,6 +1545,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
todo: todo:
required: required:
- title - title
@@ -1518,6 +1559,7 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
todo: todo:
required: required:
- title - title
@@ -1531,8 +1573,14 @@ definitions:
title: Title title: Title
type: string type: string
maxLength: 50 maxLength: 50
minLength: 1
readOnly: true readOnly: true
readOnly: true readOnly: true
example:
title: parent
todo:
title: child
todo: null
UserSerializerrr: UserSerializerrr:
required: required:
- username - username
@@ -1551,6 +1599,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
@@ -1572,6 +1621,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?
+16 -4
View File
@@ -11,17 +11,18 @@ import pytest
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.management import call_command from django.core.management import call_command
from drf_yasg import openapi
from drf_yasg.codecs import yaml_sane_load from drf_yasg.codecs import yaml_sane_load
from drf_yasg.generators import OpenAPISchemaGenerator
def call_generate_swagger(output_file='-', overwrite=False, format='', api_url='', def call_generate_swagger(output_file='-', overwrite=False, format='', api_url='',
mock=False, user='', private=False, **kwargs): mock=False, user='', private=False, generator_class_name='', **kwargs):
out = StringIO() out = StringIO()
call_command( call_command(
'generate_swagger', stdout=out, 'generate_swagger', stdout=out,
output_file=output_file, overwrite=overwrite, format=format, output_file=output_file, overwrite=overwrite, format=format, api_url=api_url, mock=mock, user=user,
api_url=api_url, mock=mock, user=user, private=private, private=private, generator_class_name=generator_class_name, **kwargs
**kwargs
) )
return out.getvalue() return out.getvalue()
@@ -46,6 +47,17 @@ def test_no_mock(db):
assert len(output_schema['paths']) > 0 assert len(output_schema['paths']) > 0
class EmptySchemaGenerator(OpenAPISchemaGenerator):
def get_paths(self, endpoints, components, request, public):
return openapi.Paths(paths={}), ''
def test_generator_class(db):
output = call_generate_swagger(generator_class_name='test_management.EmptySchemaGenerator')
output_schema = json.loads(output, object_pairs_hook=OrderedDict)
assert len(output_schema['paths']) == 0
def silentremove(filename): def silentremove(filename):
try: try:
os.remove(filename) os.remove(filename)
+34
View File
@@ -2,7 +2,9 @@ import json
from collections import OrderedDict from collections import OrderedDict
import pytest import pytest
from django.conf.urls import url
from rest_framework import routers, serializers, viewsets from rest_framework import routers, serializers, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response from rest_framework.response import Response
from drf_yasg import codecs, openapi from drf_yasg import codecs, openapi
@@ -113,3 +115,35 @@ def test_replaced_serializer():
responses = swagger['paths']['/details/{id}/']['get']['responses'] responses = swagger['paths']['/details/{id}/']['get']['responses']
assert '404' in responses assert '404' in responses
assert responses['404']['schema']['$ref'] == "#/definitions/Detail" assert responses['404']['schema']['$ref'] == "#/definitions/Detail"
def test_url_order():
# this view with description override should show up in the schema ...
@swagger_auto_schema(method='get', operation_description="description override")
@api_view()
def test_override(request, pk=None):
return Response({"message": "Hello, world!"})
# ... instead of this view which appears later in the url patterns
@api_view()
def test_view(request, pk=None):
return Response({"message": "Hello, world!"})
patterns = [
url(r'^/test/$', test_override),
url(r'^/test/$', test_view),
]
generator = OpenAPISchemaGenerator(
info=openapi.Info(title="Test generator", default_version="v1"),
version="v2",
url='',
patterns=patterns
)
# description override is successful
swagger = generator.get_schema(None, True)
assert swagger['paths']['/test/']['get']['description'] == 'description override'
# get_endpoints only includes one endpoint
assert len(generator.get_endpoints(None)['/test/'][1]) == 1
+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())
+1 -1
View File
@@ -46,7 +46,7 @@ commands =
[pytest] [pytest]
DJANGO_SETTINGS_MODULE = testproj.settings.local DJANGO_SETTINGS_MODULE = testproj.settings.local
python_paths = testproj python_paths = testproj
addopts = -n 3 addopts = -n 3 --ignore=node_modules
[flake8] [flake8]
max-line-length = 120 max-line-length = 120