Compare commits

..

54 Commits

Author SHA1 Message Date
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
Cristi Vîjdea 4e7fa28744 Superficial fixes 2018-04-27 01:53:05 +03:00
Roman Sichny 979ec84630 Django rest framework recursive support (#110)
* add get_serializer_ref_name utility function
* implement RecursiveFieldInspector
* add option to allow non-existing reference in SchemaRef
* add examples and README
* Update changelog and docs
2018-04-27 01:51:10 +03:00
Cristi Vîjdea d2dc09cb3c Fix changelog markup 2018-04-25 23:04:43 +03:00
Cristi Vîjdea 36992072ca Add 1.6.2 changelog 2018-04-25 22:58:02 +03:00
Cristi Vîjdea aa90723703 Switch to redoc 2.0 alpha
Update redoc to 2.0.0-alpha.17
2018-04-25 22:55:25 +03:00
Cristi Vîjdea 301511bebc Update swagger-ui to 3.13.6 2018-04-25 22:44:49 +03:00
Cristi Vîjdea c0f37f6ec1 Avoid crash when hitting unknown model fields
Fixes #102
2018-04-25 22:41:06 +03:00
Tobias Krönke 5e684549a1 Correct values in swagger-ui docs (#108) 2018-04-25 17:53:22 +03:00
John Carter 322971f3e7 Make parameters order stable for multi-parameter URLs (#106)
Fixes #105

* Added intermittently failing test for #105
* Make parameter order stable for urls with multiple params
2018-04-23 19:16:22 +03:00
Cristi Vîjdea 6dd8ded05d Update swagger-ui to 3.13.3 2018-04-09 13:55:17 +03:00
Cristi Vîjdea 7270154828 Test with Django Rest Framework 3.8 (#96)
* Add djangorestframework 3.8 to tox and travis
* Add @action tests
* Limit tox to <3.0.0
2018-04-04 22:59:57 +03:00
Cristi Vîjdea 6f7d14fdb2 Add 1.6.1 changelog 2018-04-01 12:08:14 +03:00
shahha 941ec8fdaf Added SUPPORTED_SUBMIT_METHODS swagger ui setting (#91) 2018-03-26 11:15:28 +03:00
Cristi Vîjdea 51ec07261d Improve OAuth2 behaviour and documentation (#90)
* Set OAUTH2_REDIRECT_URL to oauth2-redirect.html by default
* Add example SWAGGER_SETTINGS for OAuth
* Add note about redirect URL
2018-03-24 13:05:37 +02:00
Cristi Vîjdea a9cdf6d561 Fix type of properties in Schema docstring
Fixes #87.
2018-03-21 13:39:14 +02:00
Cristi Vîjdea a64ce95e3c Reset testproj migrations
Heroku deployment issues...
2018-03-18 20:35:02 +02:00
Cristi Vîjdea c9147a5746 Fix testproj people app 2018-03-18 20:20:04 +02:00
Cristi Vîjdea ccdf646c0e Run isort 2018-03-18 20:01:21 +02:00
Cristi Vîjdea 04252ebec3 Remove reodc-alpha artifacts 2018-03-18 19:52:16 +02:00
Cristi Vîjdea 848fb69009 Update swagger-ui to 3.13.0 2018-03-18 19:32:21 +02:00
ko-pp 309a6eb8cd Fix schema generation with OneToOneFields (#81)
* Fix: OneToOneRel, used by OneToOneField doesn't have help_text nor primary_key attributes, thus breaking OpenAPISchemaGenerator; use hasattr() as safe-guard.
* Fix: use getattr() with a default value instead of hasattr() + acessing the value
* Add: 'people' app that breaks drf_yasg without previous commits
* Update tests/references.yaml + run isort and flake8
* Fix: set on_delete for Person.identity as Django-2+ requires it
2018-03-18 19:30:36 +02:00
67 changed files with 2183 additions and 554 deletions
+2
View File
@@ -159,3 +159,5 @@ com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
\.pytest_cache/
+2
View File
@@ -8,6 +8,7 @@
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
@@ -15,6 +16,7 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/testproj" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/docs/_build" />
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.6 (drf-yasg)" jdkType="Python SDK" />
+2 -1
View File
@@ -10,11 +10,12 @@
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ourVersions">
<value>
<list size="4">
<list size="5">
<item index="0" class="java.lang.String" itemvalue="2.7" />
<item index="1" class="java.lang.String" itemvalue="3.4" />
<item index="2" class="java.lang.String" itemvalue="3.5" />
<item index="3" class="java.lang.String" itemvalue="3.6" />
<item index="4" class="java.lang.String" itemvalue="3.7" />
</list>
</value>
</option>
+3
View File
@@ -70,4 +70,7 @@
</LinkMapSettings>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (drf-yasg)" project-jdk-type="Python SDK" />
<component name="PythonCompatibilityInspectionAdvertiser">
<option name="version" value="3" />
</component>
</project>
+4 -1
View File
@@ -2,17 +2,20 @@ language: python
cache: pip
python:
- '2.7'
- '3.4'
- '3.5'
- '3.6'
env:
- DRF=3.7
- DRF=3.8
jobs:
include:
- stage: test
python: '2.7'
env: DRF=3.7
-
python: '3.6'
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
$ source venv/bin/activate
(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**
+7 -1
View File
@@ -11,7 +11,7 @@ Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framewor
Compatible with
- **Django Rest Framework**: 3.7.7
- **Django Rest Framework**: 3.7.7, 3.8.x
- **Django**: 1.11.x, 2.0.x
- **Python**: 2.7, 3.4, 3.5, 3.6
@@ -353,6 +353,12 @@ Integration with `djangorestframework-camel-case <https://github.com/vbabiy/djan
provided out of the box - if you have ``djangorestframework-camel-case`` installed and your ``APIView`` uses
``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer``, all property names will be converted to *camelCase* by default.
djangorestframework-recursive
===============================
Integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_ is
provided out of the box - if you have ``djangorestframework-recursive`` installed.
.. |travis| image:: https://img.shields.io/travis/axnsan12/drf-yasg/master.svg
:target: https://travis-ci.org/axnsan12/drf-yasg
:alt: Travis CI
+115
View File
@@ -3,6 +3,121 @@ Changelog
#########
*********
**1.9.0**
*********
*Release date: Jun 16, 2018*
- **ADDED:** added ``DEFAULT_GENERATOR_CLASS`` setting and ``--generator-clas`` 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**
*********
*Release date: Apr 27, 2018*
- **ADDED:** added integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_
(:issue:`109`, :pr:`110`, thanks to :ghuser:`rsichny`)
*NOTE:* in order for this to work, you will have to add the new ``drf_yasg.inspectors.RecursiveFieldInspector`` to
your ``DEFAULT_FIELD_INSPECTORS`` array if you changed it from the default value
- **FIXED:** ``SchemaRef`` now supports cyclical references via the ``ignore_unresolved`` argument
*********
**1.6.2**
*********
*Release date: Apr 25, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.13.6
- **IMPROVED:** switched ``ReDoc`` to version 2.0.0-alpha.17 (was 1.21.2); fixes :issue:`107`
- **FIXED:** made documentation ordering of parameters stable for urls with multiple parameters (:issue:`105`, :pr:`106`)
- **FIXED:** fixed crash when using a model ``ChoiceField`` of unknown child type
*********
**1.6.1**
*********
*Release date: Apr 01, 2018*
- **ADDED:** added ``SUPPORTED_SUBMIT_METHODS`` ``swagger-ui`` setting
*********
**1.6.0**
*********
*Release date: Mar 24, 2018*
- **IMPROVED:** ``OAUTH2_REDIRECT_URL`` will now default to the built in ``oauth2-redirect.html`` file
*********
**1.5.1**
*********
*Release date: Mar 18, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.13.0
- **FIXED:** fixed a crash caused by ``serializers.OneToOneRel`` (:pr:`81`, thanks to :ghuser:`ko-pp`)
*********
**1.5.0**
*********
+1 -1
View File
@@ -273,7 +273,7 @@ def role_github_user(name, rawtext, text, lineno, inliner, options=None, content
options = options or {}
content = content or []
if not re.match(r"^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$", text):
if not re.match(r"^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$", text, re.IGNORECASE):
return sphinx_err(inliner, lineno, rawtext, '"%s" is not a valid GitHub username.' % text)
ref = gh_user_uri.format(text)
+11 -5
View File
@@ -87,8 +87,8 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
* for ``ViewSet``, ``GenericViewSet``, ``ModelViewSet``, because each viewset corresponds to multiple **paths**, you have
to decorate the *action methods*, i.e. ``list``, ``create``, ``retrieve``, etc. |br|
Additionally, ``@list_route``\ s or ``@detail_route``\ s defined on the viewset, like function based api views, can
respond to multiple HTTP methods and thus have multiple operations that must be decorated separately:
Additionally, ``@action``\ s, `@list_route``\ s or ``@detail_route``\ s defined on the viewset, like function based
api views, can respond to multiple HTTP methods and thus have multiple operations that must be decorated separately:
.. code-block:: python
@@ -96,13 +96,13 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
class ArticleViewSet(viewsets.ModelViewSet):
# method or 'methods' can be skipped because the list_route only handles a single method (GET)
@swagger_auto_schema(operation_description='GET /articles/today/')
@list_route(methods=['get'])
@action(detail=False, methods=['get'])
def today(self, request):
...
@swagger_auto_schema(method='get', operation_description="GET /articles/{id}/image/")
@swagger_auto_schema(method='post', operation_description="POST /articles/{id}/image/")
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
@action(detail=True, methods=['get', 'post'], parser_classes=(MultiPartParser,))
def image(self, request, id=None):
...
@@ -169,13 +169,19 @@ You can define some per-serializer options by adding a ``Meta`` class to your se
class Meta:
... 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
``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.
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``)
* ``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>`_.
*************************
+35 -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.
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
:ref:`SECURITY_REQUIREMENTS <security-definitions-settings>` setting.
@@ -63,3 +63,37 @@ settings described below were added as a result of discussion in issue :issue:`5
The settings of interest can be found on the :ref:`settings page <oauth2-settings>`. Configuration options are similar
to most OAuth client setups like web or mobile applications. Reading the relevant ``swagger-ui`` docmentation linked
will also probably help.
Example
^^^^^^^
A very simple working configuration was provided by :ghuser:`Vigrond`, originally at
`https://github.com/Vigrond/django_oauth2_example <https://github.com/Vigrond/django_oauth2_example>`_.
.. code-block:: python
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False,
'SECURITY_DEFINITIONS': {
'Your App API - Swagger': {
'type': 'oauth2',
'authorizationUrl': '/yourapp/o/authorize',
'tokenUrl': '/yourapp/o/token/',
'flow": "accessCode',
'scopes': {
'read:groups': 'read groups',
}
}
},
'OAUTH2_CONFIG': {
'clientId': 'yourAppClientId',
'clientSecret': 'yourAppClientSecret',
'appName': 'your application name'
},
}
If the OAuth2 provider requires you to provide the full absolute redirect URL, the default value for most
``staticfiles`` configurations will be ``<origin>/static/drf-yasg/swagger-ui-dist/oauth2-redirect.html``. If this is
not suitable for some reason, you can override the ``OAUTH2_REDIRECT_URL`` setting as appropriate.
+40 -10
View File
@@ -43,6 +43,14 @@ The possible settings and their default values are as follows:
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
-------------------------
@@ -67,6 +75,7 @@ to this list.
:class:`'drf_yasg.inspectors.FileFieldInspector' <.inspectors.FileFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.DictFieldInspector' <.inspectors.DictFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.HiddenFieldInspector' <.inspectors.HiddenFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.RecursiveFieldInspector' <.inspectors.RecursiveFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \
``]``
@@ -101,7 +110,7 @@ DEFAULT_INFO
------------
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`
@@ -190,8 +199,8 @@ OPERATIONS_SORTER
Sorting order for the operation list of each tag.
* :python:`None`: show in the order returned by the server
* :python:`alpha`: sort alphabetically by path
* :python:`method`: sort by HTTP method
* :python:`'alpha'`: sort alphabetically by path
* :python:`'method'`: sort by HTTP method
**Default**: :python:`None` |br|
*Maps to parameter*: ``operationsSorter``
@@ -202,7 +211,7 @@ TAGS_SORTER
Sorting order for tagged operation groups.
* :python:`None`: Swagger UI default ordering
* :python:`alpha`: sort alphabetically
* :python:`'alpha'`: sort alphabetically
**Default**: :python:`None` |br|
*Maps to parameter*: ``tagsSorter``
@@ -212,9 +221,9 @@ DOC_EXPANSION
Controls the default expansion setting for the operations and tags.
* :python:`None`: everything is collapsed
* :python:`list`: only tags are expanded
* :python:`full`: all operations are expanded
* :python:`'none'`: everything is collapsed
* :python:`'list'`: only tags are expanded
* :python:`'full'`: all operations are expanded
**Default**: :python:`'list'` |br|
*Maps to parameter*: ``docExpansion``
@@ -240,8 +249,8 @@ DEFAULT_MODEL_RENDERING
Controls whether operations show the model structure or the example value by default.
* :python:`model`: show the model fields by default
* :python:`example`: show the example value by default
* :python:`'model'`: show the model fields by default
* :python:`'example'`: show the example value by default
**Default**: :python:`'model'` |br|
*Maps to parameter*: ``defaultModelRendering``
@@ -254,12 +263,24 @@ Controls how many levels are expaned by default when showing nested models.
**Default**: :python:`3` |br|
*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_REDIRECT_URL
-------------------
Used when OAuth2 authenitcation of API requests via swagger-ui is desired.
Used when OAuth2 authenitcation of API requests via swagger-ui is desired. If ``None`` is passed, the
``oauth2RedirectUrl`` parameter will be set to ``{% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}``. This
is the default `https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html <oauth2-redirect>`_
file provided by ``swagger-ui``.
**Default**: :python:`None` |br|
*Maps to parameter*: ``oauth2RedirectUrl``
@@ -273,6 +294,15 @@ to the ``SwaggerUIBundle#initOAuth`` method, and must be a dictionary. See
**Default**: :python:`{}`
SUPPORTED_SUBMIT_METHODS
------------------------
List of HTTP methods that have the Try it out feature enabled. An empty array disables Try it out for all operations.
This does not filter the operations from the display.
**Default**: :python:`['get','put','post','delete','options','head','patch','trace']` |br|
*Maps to parameter*: ``supportedSubmitMethods``
******************
``REDOC_SETTINGS``
******************
+838 -201
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,8 +1,8 @@
{
"name": "drf-yasg",
"dependencies": {
"redoc": "^1.21.2",
"swagger-ui-dist": "^3.12.1"
"redoc": "^2.0.0-alpha.22",
"swagger-ui-dist": "^3.16.0"
},
"repository": {
"type": "git",
+1 -2
View File
@@ -8,5 +8,4 @@ six>=1.10.0
uritemplate>=3.0.0
djangorestframework>=3.7.7
Django>=1.11.7,<2.0; python_version <= "2.7"
Django>=1.11.7; python_version >= "3.4"
Django>=1.11.7
+1 -2
View File
@@ -3,8 +3,7 @@ pytest>=2.9
pytest-pythonpath>=0.7.1
pytest-cov>=2.5.1
pytest-xdist>=1.22.0
# latest pip version of pytest-django is more than a year old and does not support Django 2.0
git+https://github.com/pytest-dev/pytest-django.git@94cccb956435dd7a719606744ee7608397e1eafb
pytest-django>=3.2.0
datadiff==2.0.0
-r testproj.txt
+1
View File
@@ -5,5 +5,6 @@ django-cors-headers>=2.1.0
django-filter>=1.1.0,<2.0; python_version == "2.7"
django-filter>=1.1.0; python_version >= "3.4"
djangorestframework-camel-case>=0.2.0
djangorestframework-recursive>=0.1.2
dj-database-url>=0.4.2
user_agents>=1.1.0
+1 -1
View File
@@ -1,5 +1,5 @@
# requirements for building and running tox
tox>=2.9.1
tox>=2.9.1,<3.0.0
detox>=0.11
-r setup.txt
+15 -1
View File
@@ -2,16 +2,18 @@ from django.conf import settings
from rest_framework.settings import perform_import
SWAGGER_DEFAULTS = {
'DEFAULT_GENERATOR_CLASS': 'drf_yasg.generators.OpenAPISchemaGenerator',
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.inspectors.SwaggerAutoSchema',
'DEFAULT_FIELD_INSPECTORS': [
'drf_yasg.inspectors.CamelCaseJSONFilter',
'drf_yasg.inspectors.RecursiveFieldInspector',
'drf_yasg.inspectors.ReferencingSerializerInspector',
'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.ChoiceFieldInspector',
'drf_yasg.inspectors.FileFieldInspector',
'drf_yasg.inspectors.DictFieldInspector',
'drf_yasg.inspectors.HiddenFieldInspector',
'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.SimpleFieldInspector',
'drf_yasg.inspectors.StringDefaultFieldInspector',
],
@@ -44,8 +46,19 @@ SWAGGER_DEFAULTS = {
'SHOW_EXTENSIONS': True,
'DEFAULT_MODEL_RENDERING': 'model',
'DEFAULT_MODEL_DEPTH': 3,
'SHOW_COMMON_EXTENSIONS': True,
'OAUTH2_REDIRECT_URL': None,
'OAUTH2_CONFIG': {},
'SUPPORTED_SUBMIT_METHODS': [
'get',
'put',
'post',
'delete',
'options',
'head',
'patch',
'trace'
],
}
REDOC_DEFAULTS = {
@@ -56,6 +69,7 @@ REDOC_DEFAULTS = {
}
IMPORT_STRINGS = [
'DEFAULT_GENERATOR_CLASS',
'DEFAULT_AUTO_SCHEMA_CLASS',
'DEFAULT_FIELD_INSPECTORS',
'DEFAULT_FILTER_INSPECTORS',
+27 -14
View File
@@ -86,14 +86,17 @@ class EndpointEnumerator(_EndpointEnumerator):
for pattern in patterns:
path_regex = prefix + get_original_route(pattern)
if isinstance(pattern, URLPattern):
path = self.get_path_from_regex(path_regex)
callback = pattern.callback
url_name = pattern.name
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
path = self.replace_version(path, callback)
for method in self.get_allowed_methods(callback):
endpoint = (path, method, callback)
api_endpoints.append(endpoint)
try:
path = self.get_path_from_regex(path_regex)
callback = pattern.callback
url_name = pattern.name
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
path = self.replace_version(path, callback)
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):
nested_endpoints = self.get_api_endpoints(
@@ -204,9 +207,15 @@ class OpenAPISchemaGenerator(object):
paths, prefix = self.get_paths(endpoints, components, request, public)
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
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
if url is None and request is not None:
@@ -315,7 +324,9 @@ class OpenAPISchemaGenerator(object):
if not public and not self._gen.has_view_permissions(path, method, view):
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:
# since the common prefix is used as the API basePath, it must be stripped
@@ -356,6 +367,9 @@ class OpenAPISchemaGenerator(object):
view_inspector = view_inspector_cls(view, path, method, components, request, overrides)
operation = view_inspector.get_operation(operation_keys)
if operation is None:
return None
if 'consumes' in operation and set(operation.consumes) == set(self.consumes):
del operation.consumes
if 'produces' in operation and set(operation.produces) == set(self.produces):
@@ -401,17 +415,16 @@ class OpenAPISchemaGenerator(object):
"""
parameters = []
queryset = getattr(view_cls, 'queryset', None)
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
for variable in uritemplate.variables(path):
for variable in sorted(uritemplate.variables(path)):
model, model_field = get_queryset_field(queryset, variable)
attrs = get_basic_type_info(model_field) or {'type': openapi.TYPE_STRING}
if getattr(view_cls, 'lookup_field', None) == variable and attrs['type'] == openapi.TYPE_STRING:
attrs['pattern'] = getattr(view_cls, 'lookup_value_regex', attrs.get('pattern', None))
if model_field and model_field.help_text:
if model_field and getattr(model_field, 'help_text', False):
description = force_text(model_field.help_text)
elif model_field and model_field.primary_key:
elif model_field and getattr(model_field, 'primary_key', False):
description = get_pk_description(model, model_field)
else:
description = None
+6 -6
View File
@@ -3,9 +3,9 @@ from .base import (
BaseInspector, FieldInspector, FilterInspector, NotHandled, PaginatorInspector, SerializerInspector, ViewInspector
)
from .field import (
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, InlineSerializerInspector,
ReferencingSerializerInspector, RelatedFieldInspector, SimpleFieldInspector, StringDefaultFieldInspector,
HiddenFieldInspector,
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector,
InlineSerializerInspector, RecursiveFieldInspector, ReferencingSerializerInspector, RelatedFieldInspector,
SimpleFieldInspector, StringDefaultFieldInspector
)
from .query import CoreAPICompatInspector, DjangoRestResponsePagination
from .view import SwaggerAutoSchema
@@ -23,9 +23,9 @@ __all__ = [
'CoreAPICompatInspector', 'DjangoRestResponsePagination',
# field inspectors
'InlineSerializerInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector', 'SimpleFieldInspector',
'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector', 'StringDefaultFieldInspector',
'CamelCaseJSONFilter', 'HiddenFieldInspector',
'InlineSerializerInspector', 'RecursiveFieldInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector',
'SimpleFieldInspector', 'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector',
'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector',
# view inspectors
'SwaggerAutoSchema',
+4 -1
View File
@@ -276,7 +276,10 @@ class SerializerInspector(FieldInspector):
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
field_inspectors = [] #:
+70 -19
View File
@@ -10,7 +10,7 @@ from rest_framework.settings import api_settings as rest_framework_settings
from .. import openapi
from ..errors import SwaggerGenerationError
from ..utils import decimal_as_float, filter_none
from ..utils import decimal_as_float, filter_none, get_serializer_ref_name
from .base import FieldInspector, NotHandled, SerializerInspector
logger = logging.getLogger(__name__)
@@ -22,12 +22,36 @@ class InlineSerializerInspector(SerializerInspector):
#: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section
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):
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_):
fields = getattr(serializer, 'fields', {})
return [
parameters = [
self.probe_field_inspectors(
value, openapi.Parameter, self.use_definitions,
name=self.get_parameter_name(key), in_=in_
@@ -36,12 +60,17 @@ class InlineSerializerInspector(SerializerInspector):
in fields.items()
]
return self.add_manual_parameters(serializer, parameters)
def get_property_name(self, field_name):
return field_name
def get_parameter_name(self, 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):
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
@@ -55,33 +84,24 @@ class InlineSerializerInspector(SerializerInspector):
if swagger_object_type != openapi.Schema:
raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__)
serializer = field
serializer_meta = getattr(serializer, 'Meta', None)
serializer_name = type(serializer).__name__
if hasattr(serializer_meta, 'ref_name'):
ref_name = serializer_meta.ref_name
elif serializer_name == 'NestedSerializer' and isinstance(serializer, serializers.ModelSerializer):
logger.debug("Forcing inline output for ModelSerializer named 'NestedSerializer': " + str(serializer))
ref_name = None
else:
ref_name = serializer_name
if ref_name.endswith('Serializer'):
ref_name = ref_name[:-len('Serializer')]
ref_name = self.get_serializer_ref_name(field)
def make_schema_definition():
properties = OrderedDict()
required = []
for property_name, child in serializer.fields.items():
for property_name, child in field.fields.items():
property_name = self.get_property_name(property_name)
prop_kwargs = {
'read_only': child.read_only or None
'read_only': bool(child.read_only) or None
}
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
)
if child.required:
properties[property_name] = child_schema
if child.required and not getattr(child_schema, 'read_only', False):
required.append(property_name)
result = SwaggerType(
@@ -94,6 +114,10 @@ class InlineSerializerInspector(SerializerInspector):
# but is visually displayed like the model name, which is confusing
# it is better to just remove title from inline models
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
if not ref_name or not use_references:
@@ -292,6 +316,10 @@ def find_limits(field):
if attr not in limits or improves(limit_value, limits[attr]):
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()))
@@ -410,7 +438,9 @@ class ChoiceFieldInspector(FieldInspector):
model = getattr(getattr(serializer, 'Meta'), 'model')
model_field = get_model_field(model, field.source)
if model_field:
enum_type = get_basic_type_info(model_field).get('type', enum_type)
model_type = get_basic_type_info(model_field)
if model_type:
enum_type = model_type.get('type', enum_type)
if isinstance(field, serializers.MultipleChoiceField):
return SwaggerType(
@@ -529,3 +559,24 @@ else:
return camelize_schema(result, self.components)
return result
try:
from rest_framework_recursive.fields import RecursiveField
except ImportError: # pragma: no cover
class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
pass
else:
class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema:
assert use_references is True, "Can not create schema for RecursiveField when use_references is False"
ref_name = get_serializer_ref_name(field.proxied)
assert ref_name is not None, "Can not create RecursiveField schema for inline ModelSerializer"
return openapi.SchemaRef(self.components.with_scope(openapi.SCHEMA_DEFINITIONS), ref_name,
ignore_unresolved=True)
return NotHandled
+5 -2
View File
@@ -48,7 +48,7 @@ class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
in_=location_to_in[field.location],
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
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)),
('results', response_schema),
)),
required=['count', 'results']
required=['results']
)
if has_count:
paged_schema.required.insert(0, 'count')
return paged_schema
+13 -3
View File
@@ -1,3 +1,4 @@
import logging
from collections import OrderedDict
from rest_framework.request import is_form_media_type
@@ -12,6 +13,8 @@ from ..utils import (
)
from .base import ViewInspector
log = logging.getLogger(__name__)
class SwaggerAutoSchema(ViewInspector):
def __init__(self, view, path, method, components, request, overrides):
@@ -83,7 +86,11 @@ class SwaggerAutoSchema(ViewInspector):
"""
if not hasattr(self.view, 'get_serializer'):
return None
return self.view.get_serializer()
try:
return self.view.get_serializer()
except Exception:
log.warning("view's get_serializer raised exception (%s)", type(self.view).__name__, exc_info=True)
return None
def get_request_serializer(self):
"""Return the request serializer (used for parsing the request payload) for this endpoint.
@@ -101,7 +108,7 @@ class SwaggerAutoSchema(ViewInspector):
if isinstance(body_override, openapi.Schema.OR_REF):
return 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 None
@@ -144,8 +151,11 @@ class SwaggerAutoSchema(ViewInspector):
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_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?")
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))
return list(parameters.values())
@@ -2,6 +2,7 @@ import json
import logging
import os
from collections import OrderedDict
from importlib import import_module
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
@@ -12,7 +13,15 @@ from rest_framework.views import APIView
from ... import openapi
from ...app_settings import swagger_settings
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):
@@ -64,6 +73,11 @@ class Command(BaseCommand):
'OpenAPISchemaGenerator.get_schema().\n'
'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):
if format == 'json':
@@ -89,7 +103,8 @@ class Command(BaseCommand):
request = APIView().initialize_request(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
logging.disable(logging.WARNING)
@@ -117,7 +132,8 @@ class Command(BaseCommand):
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,
url=api_url
)
+13 -10
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
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)
@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
SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable
: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[str] consumes: consumed MIME types; can be overriden in Operation
:param list[str] produces: produced MIME types; can be overriden in Operation
@@ -425,7 +425,7 @@ class Schema(SwaggerDict):
:param str format: value format, see OpenAPI spec
:param list enum: restrict possible values
:param str pattern: pattern if type is ``string``
:param list[.Schema,.SchemaRef] properties: object properties; required if `type` is ``object``
:param dict[str,(.Schema,.SchemaRef)] properties: object properties; required if `type` is ``object``
:param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties`
:param list[str] required: list of requried property names
:param .Schema,.SchemaRef items: type of array items, only valid if `type` is ``array``
@@ -437,7 +437,7 @@ class Schema(SwaggerDict):
super(Schema, self).__init__(**extra)
if required is True or required is False:
# common error
raise AssertionError("the `requires` attribute of schema must be an "
raise AssertionError("the `required` attribute of schema must be an "
"array of required property names, not a boolean!")
assert type, "type is required!"
self.title = title
@@ -466,7 +466,7 @@ class Schema(SwaggerDict):
class _Ref(SwaggerDict):
ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$")
def __init__(self, resolver, name, scope, expected_type):
def __init__(self, resolver, name, scope, expected_type, ignore_unresolved=False):
"""Base class for all reference types. A reference object has only one property, ``$ref``, which must be a JSON
reference to a valid object in the specification, e.g. ``#/definitions/Article`` to refer to an article model.
@@ -474,13 +474,15 @@ class _Ref(SwaggerDict):
:param str name: referenced object name, e.g. "Article"
:param str scope: reference scope, e.g. "definitions"
:param type[.SwaggerDict] expected_type: the expected type that will be asserted on the object found in resolver
:param bool ignore_unresolved: allow the reference to be not defined in resolver
"""
super(_Ref, self).__init__()
assert not type(self) == _Ref, "do not instantiate _Ref directly"
ref_name = "#/{scope}/{name}".format(scope=scope, name=name)
obj = resolver.get(name, scope)
assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \
.format(actual=type(obj).__name__, expected=expected_type.__name__)
if not ignore_unresolved:
obj = resolver.get(name, scope)
assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \
.format(actual=type(obj).__name__, expected=expected_type.__name__)
self.ref = ref_name
def resolve(self, resolver):
@@ -502,14 +504,15 @@ class _Ref(SwaggerDict):
class SchemaRef(_Ref):
def __init__(self, resolver, schema_name):
def __init__(self, resolver, schema_name, ignore_unresolved=False):
"""Adds a reference to a named Schema defined in the ``#/definitions/`` object.
:param .ReferenceResolver resolver: component resolver which must contain the definition
:param str schema_name: schema name
:param bool ignore_unresolved: allow the reference to be not defined in resolver
"""
assert SCHEMA_DEFINITIONS in resolver.scopes
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema)
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema, ignore_unresolved)
Schema.OR_REF = (Schema, SchemaRef)
+11 -11
View File
@@ -1,5 +1,5 @@
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 drf_yasg.openapi import Swagger
@@ -10,7 +10,7 @@ from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
class _SpecRenderer(BaseRenderer):
"""Base class for text renderers. Handles encoding and validation."""
charset = None
charset = 'utf-8'
validators = []
codec_class = None
@@ -22,6 +22,12 @@ class _SpecRenderer(BaseRenderer):
def render(self, data, media_type=None, renderer_context=None):
assert self.codec_class, "must override codec_class"
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)
@@ -53,7 +59,7 @@ class _UIRenderer(BaseRenderer):
template = ''
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``
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58
@@ -93,7 +99,9 @@ class _UIRenderer(BaseRenderer):
'defaultModelRendering': swagger_settings.DEFAULT_MODEL_RENDERING,
'defaultModelExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
'defaultModelsExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
'showCommonExtensions': swagger_settings.SHOW_COMMON_EXTENSIONS,
'oauth2RedirectUrl': swagger_settings.OAUTH2_REDIRECT_URL,
'supportedSubmitMethods': swagger_settings.SUPPORTED_SUBMIT_METHODS,
}
data = {k: v for k, v in data.items() if v is not None}
if swagger_settings.VALIDATOR_URL != '':
@@ -131,11 +139,3 @@ class ReDocRenderer(_UIRenderer):
"""
template = 'drf-yasg/redoc.html'
format = 'redoc'
class ReDocAlphaRenderer(_UIRenderer):
"""Renders a ReDoc web interface for schema browisng.
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
"""
template = 'drf-yasg/redoc-alpha.html'
format = 'redoc'
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
File diff suppressed because one or more lines are too long
@@ -38,7 +38,7 @@ function initSwaggerUi() {
],
layout: "StandaloneLayout",
filter: true,
requestInterceptor: function(request) {
requestInterceptor: function (request) {
var headers = request.headers || {};
var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
if (csrftoken) {
@@ -49,8 +49,15 @@ function initSwaggerUi() {
};
var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML);
console.log(swaggerSettings);
if (!('oauth2RedirectUrl' in swaggerSettings)) {
var oauth2RedirectUrl = document.getElementById('oauth2-redirect-url');
if (oauth2RedirectUrl) {
swaggerSettings['oauth2RedirectUrl'] = oauth2RedirectUrl.href;
oauth2RedirectUrl.parentNode.removeChild(oauth2RedirectUrl);
}
}
console.log(swaggerSettings);
for (var p in swaggerSettings) {
if (swaggerSettings.hasOwnProperty(p)) {
swaggerConfig[p] = swaggerSettings[p];
@@ -1,18 +0,0 @@
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
</head>
<body>
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script>
<script src="{% static 'drf-yasg/redoc-alpha/redoc.standalone.js' %}"> </script>
</body>
</html>
@@ -67,6 +67,8 @@
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
<script src="{% static 'drf-yasg/swagger-ui-init.js' %}"></script>
<a id="oauth2-redirect-url" href="{% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}" class="hidden"></a>
<div id="django-session-auth" class="hidden">
{% if USE_SESSION_AUTH %}
{% csrf_token %}
+32 -9
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_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
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
@@ -114,7 +114,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
# no overrides to set, no use in doing more work
return
# if the method is a detail_route or list_route, it will have a bind_to_methods attribute
# if the method is an @action, it will have a bind_to_methods attribute
bind_to_methods = getattr(view_method, 'bind_to_methods', [])
# if the method is actually a function based view (@api_view), it will have a 'cls' attribute
view_cls = getattr(view_method, 'cls', None)
@@ -126,7 +126,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
_methods = methods
if methods or method:
assert available_methods or http_method_names, "`method` or `methods` can only be specified " \
"on @detail_route or @api_view views"
"on @action or @api_view views"
assert bool(methods) != bool(method), "specify either method or methods"
assert not isinstance(methods, str), "`methods` expects to receive a list of methods;" \
" use `method` for a single argument"
@@ -138,13 +138,13 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
assert not any(mth in existing_data for mth in _methods), "http method defined multiple times"
if available_methods:
# detail_route, list_route or api_view
# action or api_view
assert bool(http_method_names) != bool(bind_to_methods), "this should never happen"
if len(available_methods) > 1:
assert _methods, \
"on multi-method api_view, detail_route or list_route, you must specify swagger_auto_schema on " \
"a per-method basis using one of the `method` or `methods` arguments"
"on multi-method api_view, action, detail_route or list_route, you must specify " \
"swagger_auto_schema on a per-method basis using one of the `method` or `methods` arguments"
else:
# for a single-method view we assume that single method as the decorator target
_methods = _methods or available_methods
@@ -156,8 +156,9 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
view_method._swagger_auto_schema = existing_data
else:
assert not _methods, \
"the methods argument should only be specified when decorating a detail_route or list_route; you " \
"should also ensure that you put the swagger_auto_schema decorator AFTER (above) the _route decorator"
"the methods argument should only be specified when decorating an action, detail_route or " \
"list_route; you should also ensure that you put the swagger_auto_schema decorator " \
"AFTER (above) the _route decorator"
assert not existing_data, "swagger_auto_schema applied twice to method"
view_method._swagger_auto_schema = data
@@ -183,7 +184,7 @@ def is_list_view(path, method, view):
return True
if action in ('retrieve', 'update', 'partial_update', 'destroy') or detail is True or suffix == 'Instance':
# a detail_route is surely not a list route
# a detail action is surely not a list route
return False
# for GenericAPIView, if it's a detail view it can't also be a list view
@@ -294,3 +295,25 @@ def decimal_as_float(field):
if isinstance(field, serializers.DecimalField) or isinstance(field, models.DecimalField):
return not getattr(field, 'coerce_to_string', rest_framework_settings.COERCE_DECIMAL_TO_STRING)
return False
def get_serializer_ref_name(serializer):
"""
Get serializer's ref_name (or None for ModelSerializer if it is named 'NestedSerializer')
:param serializer: Serializer instance
:return: Serializer's ref_name or None for inline serializer
:rtype: str or None
"""
serializer_meta = getattr(serializer, 'Meta', None)
serializer_name = type(serializer).__name__
if hasattr(serializer_meta, 'ref_name'):
ref_name = serializer_meta.ref_name
elif serializer_name == 'NestedSerializer' and isinstance(serializer, serializers.ModelSerializer):
logger.debug("Forcing inline output for ModelSerializer named 'NestedSerializer': " + str(serializer))
ref_name = None
else:
ref_name = serializer_name
if ref_name.endswith('Serializer'):
ref_name = ref_name[:-len('Serializer')]
return ref_name
+2 -6
View File
@@ -11,16 +11,12 @@ from rest_framework.settings import api_settings
from rest_framework.views import APIView
from .app_settings import swagger_settings
from .generators import OpenAPISchemaGenerator
from .renderers import (
OpenAPIRenderer, ReDocAlphaRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
)
from .renderers import OpenAPIRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
UI_RENDERERS = {
'swagger': (SwaggerUIRenderer, ReDocRenderer),
'redoc': (ReDocRenderer, SwaggerUIRenderer),
'redoc-alpha': (ReDocAlphaRenderer, ReDocRenderer, SwaggerUIRenderer)
}
@@ -49,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,
generator_class=OpenAPISchemaGenerator,
generator_class=swagger_settings.DEFAULT_GENERATOR_CLASS,
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
"""Create a SchemaView class with default renderers and generators.
+22 -1
View File
@@ -1,8 +1,9 @@
# Generated by Django 2.0 on 2017-12-23 09:07
# Generated by Django 2.0.1 on 2018-03-18 18:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
@@ -23,8 +24,28 @@ class Migration(migrations.Migration):
('slug', models.SlugField(blank=True, help_text='slug model help_text', unique=True)),
('date_created', models.DateTimeField(auto_now_add=True)),
('date_modified', models.DateTimeField(auto_now=True)),
('article_type', models.PositiveSmallIntegerField(choices=[(1, 'first'), (2, 'second'), (3, 'third'), (7, 'seven'), (8, 'eight')], help_text='IntegerField declared on model with choices=(...) and exposed via ModelSerializer', null=True)),
('cover', models.ImageField(blank=True, upload_to='article/original/')),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='articles', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ArticleGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('title', models.CharField(help_text='title model help_text', max_length=255, unique=True)),
('slug', models.SlugField(blank=True, help_text='slug model help_text', unique=True)),
],
),
migrations.AddField(
model_name='article',
name='group',
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.PROTECT, related_name='articles_as_main', to='articles.ArticleGroup'),
),
migrations.AddField(
model_name='article',
name='original_group',
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.PROTECT, related_name='articles_as_original', to='articles.ArticleGroup'),
),
]
@@ -1,18 +0,0 @@
# Generated by Django 2.0.1 on 2018-02-26 18:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='article',
name='article_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'first'), (2, 'second'), (3, 'third'), (7, 'seven'), (8, 'eight')], help_text='IntegerField declared on model with choices=(...) and exposed via ModelSerializer', null=True),
),
]
@@ -1,36 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-10 01:42
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('articles', '0002_article_article_type'),
]
operations = [
migrations.CreateModel(
name='ArticleGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('title', models.CharField(help_text='title model help_text', max_length=255, unique=True)),
('slug', models.SlugField(blank=True, help_text='slug model help_text', unique=True)),
],
),
migrations.AddField(
model_name='article',
name='group',
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.PROTECT, related_name='articles_as_main', to='articles.ArticleGroup'),
),
migrations.AddField(
model_name='article',
name='original_group',
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.PROTECT, related_name='articles_as_original', to='articles.ArticleGroup'),
),
]
+1 -1
View File
@@ -11,7 +11,7 @@ class ArticleSerializer(serializers.ModelSerializer):
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())
original_group = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
+42 -16
View File
@@ -3,6 +3,7 @@ import datetime
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
# noinspection PyDeprecation
from rest_framework.decorators import detail_route, list_route
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import LimitOffsetPagination
@@ -89,23 +90,48 @@ class ArticleViewSet(viewsets.ModelViewSet):
swagger_schema = NoTitleAutoSchema
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@list_route(methods=['get'])
def today(self, request):
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
serializer = self.serializer_class(articles, many=True)
return Response(serializer.data)
try:
from rest_framework.decorators import action
@swagger_auto_schema(method='get', operation_description="image GET description override")
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
def image(self, request, slug=None):
"""
image method docstring
"""
pass
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@action(detail=False, methods=['get'])
def today(self, request):
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
serializer = self.serializer_class(articles, many=True)
return Response(serializer.data)
@swagger_auto_schema(method='get', operation_description="image GET description override")
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
@action(detail=True, methods=['get', 'post'], parser_classes=(MultiPartParser,))
def image(self, request, slug=None):
"""
image method docstring
"""
pass
except ImportError:
action = None
# noinspection PyDeprecation
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@list_route(methods=['get'])
def today(self, request):
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
serializer = self.serializer_class(articles, many=True)
return Response(serializer.data)
# noinspection PyDeprecation
@swagger_auto_schema(method='get', operation_description="image GET description override")
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
def image(self, request, slug=None):
"""
image method docstring
"""
pass
def update(self, request, *args, **kwargs):
"""update method docstring"""
View File
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class PeopleConfig(AppConfig):
name = 'people'
@@ -0,0 +1,30 @@
# Generated by Django 2.0.1 on 2018-03-18 18:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Identity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('firstName', models.CharField(max_length=30, null=True)),
('lastName', models.CharField(max_length=30, null=True)),
],
),
migrations.CreateModel(
name='Person',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('identity', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='person', to='people.Identity')),
],
),
]
+10
View File
@@ -0,0 +1,10 @@
from django.db import models
class Identity(models.Model):
firstName = models.CharField(max_length=30, null=True)
lastName = models.CharField(max_length=30, null=True)
class Person(models.Model):
identity = models.OneToOneField(Identity, related_name='person', on_delete=models.PROTECT)
+23
View File
@@ -0,0 +1,23 @@
from rest_framework import serializers
from .models import Identity, Person
class IdentitySerializer(serializers.ModelSerializer):
class Meta:
model = Identity
fields = '__all__'
class PersonSerializer(serializers.ModelSerializer):
identity = IdentitySerializer()
class Meta:
model = Person
fields = '__all__'
def create(self, validated_data):
identity = Identity(**validated_data['identity'])
identity.save()
validated_data['identity'] = identity
return super().create(validated_data)
+26
View File
@@ -0,0 +1,26 @@
from django.conf.urls import url
from .views import IdentityViewSet, PersonViewSet
person_list = PersonViewSet.as_view({
'get': 'list',
'post': 'create'
})
person_detail = PersonViewSet.as_view({
'get': 'retrieve',
'patch': 'partial_update',
'delete': 'destroy'
})
identity_detail = IdentityViewSet.as_view({
'get': 'retrieve',
'patch': 'partial_update',
})
urlpatterns = (
url(r'^$', person_list, name='people-list'),
url(r'^(?P<pk>[0-9]+)$', person_detail, name='person-detail'),
url(r'^(?P<person>[0-9]+)/identity$', identity_detail,
name='person-identity'),
)
+16
View File
@@ -0,0 +1,16 @@
from rest_framework import viewsets
from .models import Identity, Person
from .serializers import IdentitySerializer, PersonSerializer
class PersonViewSet(viewsets.ModelViewSet):
model = Person
queryset = Person.objects
serializer_class = PersonSerializer
class IdentityViewSet(viewsets.ModelViewSet):
model = Identity
queryset = Identity.objects
serializer_class = IdentitySerializer
+1 -1
View File
@@ -1,4 +1,4 @@
# Generated by Django 2.0 on 2017-12-23 09:07
# Generated by Django 2.0.1 on 2018-03-18 18:32
from django.conf import settings
from django.db import migrations, models
+35 -12
View File
@@ -33,6 +33,21 @@ class SnippetList(generics.ListCreateAPIView):
"""post method docstring"""
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):
"""
@@ -56,18 +71,26 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
"""patch method docstring"""
return super(SnippetDetail, self).patch(request, *args, **kwargs)
@swagger_auto_schema(manual_parameters=[
openapi.Parameter(
name='id', in_=openapi.IN_PATH,
type=openapi.TYPE_INTEGER,
description="path parameter override",
required=True
),
], responses={
status.HTTP_204_NO_CONTENT: openapi.Response(
description="This should not crash"
)
})
@swagger_auto_schema(
manual_parameters=[
openapi.Parameter(
name='id', in_=openapi.IN_PATH,
type=openapi.TYPE_INTEGER,
description="path parameter override",
required=True
),
openapi.Parameter(
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):
"""delete method docstring"""
return super(SnippetDetail, self).patch(request, *args, **kwargs)
+13 -1
View File
@@ -27,6 +27,7 @@ INSTALLED_APPS = [
'users',
'articles',
'todo',
'people'
]
MIDDLEWARE = [
@@ -93,7 +94,18 @@ SWAGGER_SETTINGS = {
'LOGIN_URL': '/admin/login',
'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
+2 -1
View File
@@ -51,7 +51,7 @@ urlpatterns = [
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
url(r'^redoc-alpha/$', SchemaView.with_ui('redoc-alpha', cache_timeout=0), name='schema-redoc-alpha'),
url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'),
url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'),
url(r'^cached/redoc/$', SchemaView.with_ui('redoc', cache_timeout=None), name='cschema-redoc'),
@@ -63,5 +63,6 @@ urlpatterns = [
url(r'^articles/', include('articles.urls')),
url(r'^users/', include('users.urls')),
url(r'^todo/', include('todo.urls')),
url(r'^people/', include('people.urls')),
url(r'^plain/', plain_view),
]
+1 -3
View File
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-21 23:26
from __future__ import unicode_literals
# Generated by Django 2.0.1 on 2018-03-18 18:32
from django.db import migrations, models
import django.db.models.deletion
+22
View File
@@ -0,0 +1,22 @@
# Generated by Django 2.0.4 on 2018-04-26 13:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('todo', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='TodoTree',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('parent', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE,
related_name='children', to='todo.TodoTree')),
],
),
]
+5
View File
@@ -13,3 +13,8 @@ class TodoAnother(models.Model):
class TodoYetAnother(models.Model):
todo = models.ForeignKey(TodoAnother, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
class TodoTree(models.Model):
parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True)
title = models.CharField(max_length=50)
+32 -1
View File
@@ -1,7 +1,10 @@
from collections import OrderedDict
from django.utils import timezone
from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from .models import Todo, TodoAnother, TodoYetAnother
from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
class TodoSerializer(serializers.ModelSerializer):
@@ -25,3 +28,31 @@ class TodoYetAnotherSerializer(serializers.ModelSerializer):
model = TodoYetAnother
fields = ('title', 'todo')
depth = 2
swagger_schema_fields = {
'example': OrderedDict([
('title', 'parent'),
('todo', OrderedDict([
('title', 'child'),
('todo', None),
])),
])
}
class TodoTreeSerializer(serializers.ModelSerializer):
children = serializers.ListField(child=RecursiveField(), source='children.all')
class Meta:
model = TodoTree
fields = ('id', 'title', 'children')
class TodoRecursiveSerializer(serializers.ModelSerializer):
parent = RecursiveField(read_only=True)
parent_id = serializers.PrimaryKeyRelatedField(queryset=TodoTree.objects.all(), pk_field=serializers.IntegerField(),
write_only=True, allow_null=True, required=False, default=None,
source='parent')
class Meta:
model = TodoTree
fields = ('id', 'title', 'parent', 'parent_id')
+8
View File
@@ -1,3 +1,4 @@
from django.conf.urls import url
from rest_framework import routers
from todo import views
@@ -6,5 +7,12 @@ router = routers.DefaultRouter()
router.register(r'', views.TodoViewSet)
router.register(r'another', views.TodoAnotherViewSet)
router.register(r'yetanother', views.TodoYetAnotherViewSet)
router.register(r'tree', views.TodoTreeView)
router.register(r'recursive', views.TodoRecursiveView)
urlpatterns = router.urls
urlpatterns += [
url(r'^(?P<todo_id>\d+)/yetanothers/(?P<yetanother_id>\d+)/$',
views.NestedTodoView.as_view(), ),
]
+19 -2
View File
@@ -1,7 +1,10 @@
from rest_framework import viewsets
from rest_framework.generics import RetrieveAPIView
from .models import Todo, TodoAnother, TodoYetAnother
from .serializer import TodoAnotherSerializer, TodoSerializer, TodoYetAnotherSerializer
from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
from .serializer import (
TodoAnotherSerializer, TodoRecursiveSerializer, TodoSerializer, TodoTreeSerializer, TodoYetAnotherSerializer
)
class TodoViewSet(viewsets.ReadOnlyModelViewSet):
@@ -20,3 +23,17 @@ class TodoAnotherViewSet(viewsets.ReadOnlyModelViewSet):
class TodoYetAnotherViewSet(viewsets.ReadOnlyModelViewSet):
queryset = TodoYetAnother.objects.all()
serializer_class = TodoYetAnotherSerializer
class NestedTodoView(RetrieveAPIView):
serializer_class = TodoYetAnotherSerializer
class TodoTreeView(viewsets.ReadOnlyModelViewSet):
queryset = TodoTree.objects.all()
serializer_class = TodoTreeSerializer
class TodoRecursiveView(viewsets.ModelViewSet):
queryset = TodoTree.objects.all()
serializer_class = TodoRecursiveSerializer
+369 -3
View File
@@ -21,10 +21,15 @@ consumes:
produces:
- application/json
securityDefinitions:
basic:
Basic:
type: basic
Bearer:
in: header
name: Authorization
type: apiKey
security:
- basic: []
- Basic: []
- Bearer: []
paths:
/articles/:
get:
@@ -202,6 +207,7 @@ paths:
type: string
pattern: ^69$
default: '69'
minLength: 1
- name: image_styles
in: formData
description: Parameter with Items
@@ -234,6 +240,113 @@ paths:
type: string
format: slug
pattern: '[a-z0-9]+(?:-[a-z0-9]+)'
/people/:
get:
operationId: people_list
description: ''
parameters: []
responses:
'200':
description: ''
schema:
type: array
items:
$ref: '#/definitions/Person'
tags:
- people
post:
operationId: people_create
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/Person'
responses:
'201':
description: ''
schema:
$ref: '#/definitions/Person'
tags:
- people
parameters: []
/people/{id}:
get:
operationId: people_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/Person'
tags:
- people
patch:
operationId: people_partial_update
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/Person'
responses:
'200':
description: ''
schema:
$ref: '#/definitions/Person'
tags:
- people
delete:
operationId: people_delete
description: ''
parameters: []
responses:
'204':
description: ''
tags:
- people
parameters:
- name: id
in: path
description: A unique integer value identifying this person.
required: true
type: integer
/people/{person}/identity:
get:
operationId: people_identity_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/Identity'
tags:
- people
patch:
operationId: people_identity_partial_update
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/Identity'
responses:
'200':
description: ''
schema:
$ref: '#/definitions/Identity'
tags:
- people
parameters:
- name: person
in: path
required: true
type: string
/plain/:
get:
operationId: plain_list
@@ -275,6 +388,24 @@ paths:
$ref: '#/definitions/Snippet'
tags:
- 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: []
/snippets/{id}/:
get:
@@ -329,9 +460,13 @@ paths:
description: path parameter override
required: true
type: integer
- name: delete_form_param
in: formData
description: this should not crash (form parameter on DELETE method)
type: integer
responses:
'204':
description: This should not crash
description: this should not crash (response object with no schema)
tags:
- snippets
parameters:
@@ -388,6 +523,129 @@ paths:
description: A unique integer value identifying this todo another.
required: true
type: integer
/todo/recursive/:
get:
operationId: todo_recursive_list
description: ''
parameters: []
responses:
'200':
description: ''
schema:
type: array
items:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
post:
operationId: todo_recursive_create
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/TodoRecursive'
responses:
'201':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
parameters: []
/todo/recursive/{id}/:
get:
operationId: todo_recursive_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
put:
operationId: todo_recursive_update
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/TodoRecursive'
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
patch:
operationId: todo_recursive_partial_update
description: ''
parameters:
- name: data
in: body
required: true
schema:
$ref: '#/definitions/TodoRecursive'
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
tags:
- todo
delete:
operationId: todo_recursive_delete
description: ''
parameters: []
responses:
'204':
description: ''
tags:
- todo
parameters:
- name: id
in: path
description: A unique integer value identifying this todo tree.
required: true
type: integer
/todo/tree/:
get:
operationId: todo_tree_list
description: ''
parameters: []
responses:
'200':
description: ''
schema:
type: array
items:
$ref: '#/definitions/TodoTree'
tags:
- todo
parameters: []
/todo/tree/{id}/:
get:
operationId: todo_tree_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoTree'
tags:
- todo
parameters:
- name: id
in: path
description: A unique integer value identifying this todo tree.
required: true
type: integer
/todo/yetanother/:
get:
operationId: todo_yetanother_list
@@ -439,6 +697,27 @@ paths:
description: A unique integer value identifying this todo.
required: true
type: integer
/todo/{todo_id}/yetanothers/{yetanother_id}/:
get:
operationId: todo_yetanothers_read
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoYetAnother'
tags:
- todo
parameters:
- name: todo_id
in: path
required: true
type: string
- name: yetanother_id
in: path
required: true
type: string
/users/:
get:
operationId: users_list
@@ -449,6 +728,7 @@ paths:
description: this field is generated from a query_serializer
required: false
type: string
minLength: 1
- name: is_staff
in: query
description: this one too!
@@ -549,6 +829,7 @@ definitions:
description: title model help_text
type: string
maxLength: 255
minLength: 1
author:
description: The ID of the user that created this article; if none is provided,
defaults to the currently logged in user.
@@ -558,6 +839,7 @@ definitions:
description: body serializer help_text
type: string
maxLength: 5000
minLength: 1
slug:
description: slug model help_text
type: string
@@ -579,6 +861,7 @@ definitions:
description: but i needed to test these 2 fields somehow
type: string
format: uri
minLength: 1
readOnly: true
uuid:
description: should articles have UUIDs?
@@ -609,6 +892,35 @@ definitions:
type: string
format: uuid
readOnly: true
Identity:
title: Identity
type: object
properties:
id:
title: ID
type: integer
readOnly: true
firstName:
title: FirstName
type: string
maxLength: 30
minLength: 1
lastName:
title: LastName
type: string
maxLength: 30
minLength: 1
Person:
required:
- identity
type: object
properties:
id:
title: ID
type: integer
readOnly: true
identity:
$ref: '#/definitions/Identity'
Project:
required:
- projectName
@@ -619,10 +931,12 @@ definitions:
title: Project name
description: Name of the project
type: string
minLength: 1
githubRepo:
title: Github repo
description: Github repository of the project
type: string
minLength: 1
Snippet:
required:
- code
@@ -644,6 +958,7 @@ definitions:
description: The ID of the user that created this snippet.
type: string
readOnly: true
minLength: 1
title: Owner as string
title:
title: Title
@@ -652,6 +967,7 @@ definitions:
code:
title: Code
type: string
minLength: 1
linenos:
title: Linenos
type: boolean
@@ -1170,6 +1486,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
TodoAnother:
required:
- title
@@ -1180,8 +1497,47 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
todo:
$ref: '#/definitions/Todo'
TodoRecursive:
required:
- title
type: object
properties:
id:
title: ID
type: integer
readOnly: true
title:
title: Title
type: string
maxLength: 50
minLength: 1
parent:
$ref: '#/definitions/TodoRecursive'
parent_id:
type: integer
title: Parent id
TodoTree:
required:
- title
- children
type: object
properties:
id:
title: ID
type: integer
readOnly: true
title:
title: Title
type: string
maxLength: 50
minLength: 1
children:
type: array
items:
$ref: '#/definitions/TodoTree'
TodoYetAnother:
required:
- title
@@ -1191,6 +1547,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
todo:
required:
- title
@@ -1204,6 +1561,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
todo:
required:
- title
@@ -1217,8 +1575,14 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
readOnly: true
readOnly: true
example:
title: parent
todo:
title: child
todo: null
UserSerializerrr:
required:
- username
@@ -1237,6 +1601,7 @@ definitions:
type: string
pattern: ^[\w.@+-]+$
maxLength: 150
minLength: 1
email:
title: Email address
type: string
@@ -1258,6 +1623,7 @@ definitions:
type: string
format: ipv4
readOnly: true
minLength: 1
last_connected_at:
title: Last connected at
description: really?
+16 -4
View File
@@ -11,17 +11,18 @@ import pytest
from django.contrib.auth.models import User
from django.core.management import call_command
from drf_yasg import openapi
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='',
mock=False, user='', private=False, **kwargs):
mock=False, user='', private=False, generator_class_name='', **kwargs):
out = StringIO()
call_command(
'generate_swagger', stdout=out,
output_file=output_file, overwrite=overwrite, format=format,
api_url=api_url, mock=mock, user=user, private=private,
**kwargs
output_file=output_file, overwrite=overwrite, format=format, api_url=api_url, mock=mock, user=user,
private=private, generator_class_name=generator_class_name, **kwargs
)
return out.getvalue()
@@ -46,6 +47,17 @@ def test_no_mock(db):
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):
try:
os.remove(filename)
+15
View File
@@ -1,3 +1,6 @@
from collections import OrderedDict
from random import shuffle
from drf_yasg import openapi
@@ -51,3 +54,15 @@ def test_trailing_underscore_stripped():
del sd.in_
assert 'in' not in sd
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())
+8 -6
View File
@@ -1,13 +1,14 @@
[tox]
envlist =
py27-django111-drf37,
py{34,35,36}-django{111,20}-drf37,
py{34,35,36}-django{111,20}-drf{37,38},
py36-django20-drfmaster,
lint, docs
[travis:env]
DRF =
3.7: drf37
3.8: drf38
master: drfmaster
[testenv]
@@ -16,6 +17,7 @@ deps =
django20: Django>=2.0,<2.1
drf37: djangorestframework>=3.7.7,<3.8
drf38: djangorestframework>=3.8.0,<3.9
# test with the latest build of django-rest-framework to get early warning of compatibility issues
drfmaster: https://github.com/encode/django-rest-framework/archive/master.tar.gz
@@ -44,7 +46,7 @@ commands =
[pytest]
DJANGO_SETTINGS_MODULE = testproj.settings.local
python_paths = testproj
addopts = -n 3
addopts = -n 3 --ignore=node_modules
[flake8]
max-line-length = 120
@@ -63,7 +65,7 @@ known_standard_library =
collections,copy,distutils,functools,inspect,io,json,logging,operator,os,pkg_resources,re,setuptools,sys,
types,warnings
known_third_party =
coreapi,coreschema,datadiff,dj_database_url,django,django_filters,djangorestframework_camel_case,flex,gunicorn,
inflection,pygments,pytest,rest_framework,ruamel,setuptools_scm,swagger_spec_validator,uritemplate,user_agents,
whitenoise
known_first_party = drf_yasg,testproj,articles,snippets,users,urlconfs
coreapi,coreschema,datadiff,dj_database_url,django,django_filters,djangorestframework_camel_case,
rest_framework_recursive,flex,gunicorn,inflection,pygments,pytest,rest_framework,ruamel,setuptools_scm,
swagger_spec_validator,uritemplate,user_agents,whitenoise
known_first_party = drf_yasg,testproj,articles,people,snippets,todo,users,urlconfs
+1 -1
View File
@@ -2,7 +2,7 @@
set -ev
npm update
cp node_modules/redoc/dist/redoc.min.js src/drf_yasg/static/drf-yasg/redoc/
cp node_modules/redoc/bundles/redoc.standalone.js src/drf_yasg/static/drf-yasg/redoc/redoc.min.js
cp -r node_modules/swagger-ui-dist src/drf_yasg/static/drf-yasg/
pushd src/drf_yasg/static/drf-yasg/swagger-ui-dist/ >/dev/null
rm -f package.json .npmignore README.md