Compare commits

...

73 Commits

Author SHA1 Message Date
Cristi Vîjdea 23ebba4207 Rename swagger_serializer_method parameter and update docs 2018-08-08 01:41:54 +03:00
Cristi Vîjdea afcba582b3 Add 1.10.0 changelog 2018-08-08 01:27:35 +03:00
Cristi Vîjdea 12f1d23048 Fix lint errors 2018-08-08 01:24:36 +03:00
Cristi Vîjdea a5eb3dfa91 Add EXCLUDED_MEDIA_TYPES setting
Closes #158.
2018-08-08 00:59:01 +03:00
Cristi Vîjdea 5cd642c9a0 Show warning on ref_name collisions
Closes #156
2018-08-08 00:58:35 +03:00
Cristi Vîjdea 3f2d2871f0 Update swagger-ui to 3.18.0 2018-08-08 00:58:08 +03:00
Cristi Vîjdea 247c1a306a Add operation_summary and deprecated to swagger_auto_schema
Closes #149, #173.
2018-08-08 00:57:30 +03:00
Cristi Vîjdea 4ca634a45b Lint with python 3.6 2018-08-07 22:54:54 +03:00
Cristi Vîjdea 37c00ab3fb Make swagger_schema_fields work on serializer Fields
Closes #167.
2018-08-07 22:54:24 +03:00
Cristi Vîjdea 65aac1da2c Make swagger_auto_schema work with action mappings
Fixes #177.
2018-08-07 22:38:36 +03:00
Cristi Vîjdea 4c069138e8 Fix lint errors 2018-08-07 21:24:36 +03:00
John Carter 748b5d3c2f Add support for SerializerMethodField (#179)
Closes #137, #179.
2018-08-07 21:23:36 +03:00
John Carter 1dd7cfe043 Spelling fixes (#180) 2018-08-07 17:30:13 +03:00
Cristi Vîjdea 33eb9d381c Fix for python 2 2018-08-07 17:28:03 +03:00
Cristi Vîjdea e80101d98c Make handling of setuptools-scm in setup more robust
Fixes #181
2018-08-07 17:19:58 +03:00
Cristi Vîjdea 8de704d7ae Update Heroku runtime 2018-08-07 17:18:05 +03:00
Cristi Vîjdea 165ac6c076 Make dummy version string PEP 440 compliant
https://www.python.org/dev/peps/pep-0440/#version-scheme
2018-08-07 16:03:39 +03:00
Cristi Vîjdea 9eb0db466c Fix Identity field names 2018-08-06 16:37:20 +03:00
Cristi Vîjdea df0f43084f Reuse pip cache on travis (remove -U) 2018-08-06 12:37:58 +03:00
Cristi Vîjdea 16b6ed7fd6 Test with Django 2.1 and Python 3.7 (#176)
* Test with Django 2.1 and Python 3.7
* Fix lint errors
* Remove setuptools-scm hack
* Factor out coverage script
* Cache .tox in travis
* Update README & docs
2018-08-06 12:24:56 +03:00
Cristi Vîjdea 904895ba3c Add 1.9.2 changelog 2018-08-03 23:43:52 +03:00
Cristi Vîjdea 79adfc19be Update swagger-ui to 3.17.6 and ReDoc to 2.0.0-alpha.32 2018-08-03 20:27:41 +03:00
Cristi Vîjdea 2965e08e39 Force descriptions to be str objects
Fixes #159
2018-08-03 20:27:31 +03:00
Cristi Vîjdea f2e05ee4c0 Fix ReDoc configuration docs link
Closes #171
2018-08-03 16:50:28 +03:00
Amoki bbc70a7e3d Allow specific version generation in command
* Add --api-version parameter
* Fix request mocking
* Add tests
2018-08-03 16:43:26 +03:00
Bang Dao ca43a7de0c Fix readme wrong caching time expected behavior (#172) 2018-08-03 16:38:18 +03:00
Антон Вахмин (Anton Vakhmin) cc43bdf5cb Fix SHOW_COMMON_EXTENSIONS docs typos (#162)
Fix copy-paste errors.
2018-08-03 16:09:35 +03:00
Étienne Noss db86981dc1 make generate_swagger work for projects without authentication (#161)
* make generate_swagger work for projects without authentication
* use get_user_model instead of importing User
2018-07-06 16:13:19 +03:00
Paul Wayper b37ce3227a Fixing ` single-quote around @list-route (#160) 2018-07-06 15:26:34 +03:00
Cristi Vîjdea 8fbab88bda Fix changelog 2018-06-30 01:55:19 +03:00
Cristi Vîjdea 58b979f4ea Fix 1.9.1 tag fuckup
Accidentally disappeared 178390a9a0
2018-06-30 01:42:02 +03:00
Cristi Vîjdea d9b6fbc1b8 Add 1.9.1 changelog 2018-06-30 00:32:07 +03:00
Cristi Vîjdea 20370d912e Update swagger-ui to 3.17.1 and ReDoc to 2.0.0-alpha.25 2018-06-30 00:32:07 +03:00
Xiaohan Zhang 178390a9a0 Add get_default_response_serializer extension point (#153)
Enables easier request/response differentiation in SwaggerAutoSchema.
2018-06-30 00:26:29 +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
59 changed files with 1846 additions and 2628 deletions
+28 -24
View File
@@ -1,26 +1,34 @@
language: python
cache: pip
sudo: false
python:
- '2.7'
- '3.4'
- '3.5'
- '3.6'
- '2.7'
- '3.4'
- '3.5'
- '3.6'
env:
- DRF=3.7
- DRF=3.8
cache:
directories:
- $HOME/.cache/pip
- .tox
before_cache:
- rm -f $HOME/.cache/pip/log/debug.log
- rm -fr .tox/log/ .tox/*/log/ .tox/*/tmp/ .tox/dist .tox/*/lib/*/site-packages/drf_yasg*
jobs:
include:
- stage: test
python: '3.6'
env: DRF=master
- # workaround for python 3.7 on travis https://github.com/travis-ci/travis-ci/issues/9815#issuecomment-401756442
stage: test
python: '3.7'
dist: xenial
sudo: required
-
python: '3.6'
env: TOXENV=djmaster
- # readthedocs uses python 3.5 for building
python: '3.5'
env: TOXENV=docs
-
python: '2.7'
python: '3.6'
env: TOXENV=lint
- stage: publish
@@ -38,7 +46,7 @@ jobs:
allow_failures:
- env: TOXENV=lint
- env: DRF=master
- env: TOXENV=djmaster
fast_finish: true
@@ -47,20 +55,16 @@ install:
before_script:
- coverage erase
- |
[[ -z "$TOXENV" && -z "$PYPI_DEPLOY" ]] && REPORT_COVERAGE="yes" || REPORT_COVERAGE="no";
echo "Reporting coverage: ${REPORT_COVERAGE}"
- |
[[ -z "$TOXENV" && ! -z "$DRF" && "$DRF" != "master" ]] && USE_DETOX="yes" || USE_DETOX="no";
echo "Using detox: ${USE_DETOX}"
script:
- 'if [[ "$USE_DETOX" == "yes" ]]; then detox; else tox; fi'
- tox
after_success:
- coverage combine
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then coverage report; fi'
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then codecov; fi'
- |
if [[ -z "$TOXENV" && -z "$PYPI_DEPLOY" ]]; then
chmod +x coverage.sh
./coverage.sh
fi
branches:
only:
+2 -2
View File
@@ -35,8 +35,8 @@ 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 -U -e .[validation]
(venv) $ pip install -U -r requirements/dev.txt
#. **Make your changes and check them against the test project**
+16 -19
View File
@@ -11,9 +11,9 @@ Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framewor
Compatible with
- **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
- **Django Rest Framework**: 3.7.7, 3.8
- **Django**: 1.11, 2.0, 2.1
- **Python**: 2.7, 3.4, 3.5, 3.6, 3.7
Resources:
@@ -85,14 +85,14 @@ The preferred instalation method is directly from pypi:
.. code:: console
pip install drf-yasg
pip install -U drf-yasg
Additionally, if you want to use the built-in validation mechanisms (see `4. Validation`_), you need to install
some extra requirements:
.. code:: console
pip install drf-yasg[validation]
pip install -U drf-yasg[validation]
.. _readme-quickstart:
@@ -134,9 +134,9 @@ In ``urls.py``:
)
urlpatterns = [
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=None), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'),
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=None), name='schema-redoc'),
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
...
]
@@ -294,7 +294,7 @@ For additional usage examples, you can take a look at the test project in the ``
$ virtualenv venv
$ source venv/bin/activate
(venv) $ cd testproj
(venv) $ pip install -r requirements.txt
(venv) $ pip install -U -r requirements.txt
(venv) $ python manage.py migrate
(venv) $ python manage.py shell -c "import createsuperuser"
(venv) $ python manage.py runserver
@@ -315,8 +315,8 @@ From here on, the terms “OpenAPI” and “Swagger” are used interchangeably
Swagger in Django Rest Framework
================================
Since Django Rest 3.7, there is now `built in support <http://www.django-rest-framework.org/api-guide/schemas/>`__ for
automatic OpenAPI 2.0 schema generation. However, this generation is based on the `coreapi <http://www.coreapi.org/>`__
Since Django Rest Framework 3.7, there is now `built in support <http://www.django-rest-framework.org/api-guide/schemas/>`__
for automatic OpenAPI 2.0 schema generation. However, this generation is based on the `coreapi <http://www.coreapi.org/>`__
standard, which for the moment is vastly inferior to OpenAPI in both features and tooling support. In particular,
the OpenAPI codec/compatibility layer provided has a few major problems:
@@ -329,18 +329,15 @@ In short this makes the generated schema unusable for code generation, and medio
Other libraries
===============
There are currently two decent Swagger schema generators that I could
find for django-rest-framework:
There are currently two decent Swagger schema generators that I could find for django-rest-framework:
* `django-rest-swagger <https://github.com/marcgibbons/django-rest-swagger>`__
* `drf-openapi <https://github.com/limdauto/drf_openapi>`__
Out of the two, ``django-rest-swagger`` is just a wrapper around DRF 3.7 schema generation with an added UI, and
thus presents the same problems. ``drf-openapi`` is a bit more involved and implements some custom handling for response
schemas, but ultimately still falls short in code generation because the responses are plain of lacking support for
named schemas.
Both projects are also currently unmantained.
``django-rest-swagger`` is just a wrapper around DRF 3.7 schema generation with an added UI, and
thus presents the same problems, while also being unmaintained. ``drf-openapi`` was
`discontinued by the author <https://github.com/limdauto/drf_openapi/commit/1673c6e039eec7f089336a83bdc31613f32f7e21>`_
on April 3rd, 2018.
************************
Third-party integrations
Executable
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -ex
coverage combine
coverage report
codecov
+113
View File
@@ -3,6 +3,119 @@ Changelog
#########
**********
**1.10.0**
**********
*Release date: Aug 08, 2018*
- **ADDED:** added ``EXCLUDED_MEDIA_TYPES`` setting for controlling ``produces`` MIME type filtering (:issue:`158`)
- **ADDED:** added support for ``SerializerMethodField``, via the ``swagger_serializer_method`` decorator for the
method field, and support for Python 3.5 style type hinting of the method field return type
(:issue:`137`, :pr:`175`, :pr:`179`)
*NOTE:* in order for this to work, you will have to add the new ``drf_yasg.inspectors.SerializerMethodFieldInspector``
to your ``DEFAULT_FIELD_INSPECTORS`` array if you changed it from the default value
- **IMPROVED:** updated ``swagger-ui`` to version 3.18.0
- **IMPROVED:** added support for Python 3.7 and Django 2.1 (:pr:`176`)
- **IMPROVED:** ``swagger_schema_fields`` will now also work on serializer ``Field``\ s (:issue:`167`)
- **IMPROVED:** ``ref_name`` collisions will now log a warning message (:issue:`156`)
- **IMPROVED:** added ``operation_summary`` and ``deprecated`` arguments to ``swagger_auto_schema``
(:issue:`149`, :issue:`173`)
- **FIXED:** made ``swagger_auto_schema`` work with DRF 3.9 ``@action`` mappings (:issue:`177`)
*********
**1.9.2**
*********
*Release date: Aug 03, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.17.6
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.32
- **IMPROVED:** added ``--api-version`` argument to the ``generate_swagger`` management command (:pr:`170`)
- **FIXED:** corrected various documentation typos (:pr:`160`, :pr:`162`, :issue:`171`, :pr:`172`)
- **FIXED:** made ``generate_swagger`` work for projects without authentication (:pr:`161`)
- **FIXED:** fixed ``SafeText`` interaction with YAML codec (:issue:`159`)
*********
**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 instance 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_schema_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**
*********
+62 -2
View File
@@ -87,7 +87,7 @@ 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, ``@action``\ s, `@list_route``\ s or ``@detail_route``\ s defined on the viewset, like function based
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:
@@ -155,6 +155,57 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
replacing/decorating methods on the base class itself.
*********************************
Support for SerializerMethodField
*********************************
Schema generation of ``serializers.SerializerMethodField`` is supported in two ways:
1) The :func:`swagger_serializer_method <.swagger_serializer_method>` decorator for the use case where the serializer
method is using a serializer. e.g.:
.. code-block:: python
from drf_yasg.utils import swagger_serializer_method
class OtherStuffSerializer(serializers.Serializer):
foo = serializers.CharField()
class ParentSerializer(serializers.Serializer):
other_stuff = serializers.SerializerMethodField()
@swagger_serializer_method(serializer_or_field=OtherStuffSerializer)
def get_other_stuff(self, obj):
return OtherStuffSerializer().data
Note that the ``serializer_or_field`` parameter can accept either a subclass or an instance of ``serializers.Field``.
2) For simple cases where the method is returning one of the supported types, `Python 3 type hinting`_ of the
serializer method return value can be used. e.g.:
.. code-block:: python
class SomeSerializer(serializers.Serializer):
some_number = serializers.SerializerMethodField()
def get_some_number(self, obj) -> float:
return 1.0
When return type hinting is not supported, the equivalent ``serializers.Field`` subclass can be used with
:func:`swagger_serializer_method <.swagger_serializer_method>`:
.. code-block:: python
class SomeSerializer(serializers.Serializer):
some_number = serializers.SerializerMethodField()
@swagger_serializer_method(serializer_or_field=serializers.FloatField)
def get_some_number(self, obj):
return 1.0
********************************
Serializer ``Meta`` nested class
********************************
@@ -169,13 +220,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>`_.
*************************
@@ -327,3 +384,6 @@ A second example, of a :class:`~.inspectors.FieldInspector` that removes the ``t
Another caveat that stems from this is that any serializer named "``NestedSerializer``" will be forced inline
unless it has a ``ref_name`` set explicitly.
.. _Python 3 type hinting: https://docs.python.org/3/library/typing.html
+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
the view
* :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
.. _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.
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.
+28 -2
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
-------------------------
@@ -68,6 +76,7 @@ to this list.
: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.SerializerMethodFieldInspector' <.inspectors.SerializerMethodFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \
``]``
@@ -96,13 +105,21 @@ Paginator inspectors given to :func:`@swagger_auto_schema <.swagger_auto_schema>
Swagger document attributes
===========================
EXCLUDED_MEDIA_TYPES
--------------------
A list of keywords for excluding MIME types from ``Operation.produces``. Any MIME type string which includes one of
the substrings in this list will be prevented from appearing in a ``produces`` array in the Swagger document.
**Default**: :python:`['html']`
.. _default-swagger-settings:
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`
@@ -255,6 +272,15 @@ Controls how many levels are expaned by default when showing nested models.
**Default**: :python:`3` |br|
*Maps to parameter*: ``defaultModelExpandDepth``
SHOW_COMMON_EXTENSIONS
----------------------
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
@@ -296,7 +322,7 @@ ReDoc UI settings
=================
ReDoc UI configuration settings. |br|
See https://github.com/Rebilly/ReDoc#redoc-tag-attributes.
See https://github.com/Rebilly/ReDoc#configuration.
LAZY_RENDERING
--------------
+207 -2163
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": "^2.0.0-alpha.17",
"swagger-ui-dist": "^3.13.6"
"redoc": "^2.0.0-alpha.32",
"swagger-ui-dist": "^3.18.0"
},
"repository": {
"type": "git",
+1
View File
@@ -1,2 +1,3 @@
-r requirements/setup.txt
.[validation]
-r requirements/heroku.txt
+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 -3
View File
@@ -1,6 +1,4 @@
# requirements for local development to be installed via pip install -r requirements/dev.txt
# requirements for local development to be installed via pip install -U -r requirements/dev.txt
-r tox.txt
-r test.txt
-r lint.txt
tox-battery>=0.5
+1 -1
View File
@@ -4,5 +4,5 @@ sphinx_rtd_theme>=0.2.4
Pillow>=4.3.0
readme_renderer>=17.2
Django>=2.0,<2.1
Django>=2.0
djangorestframework_camel_case>=0.2.0
+1 -2
View File
@@ -1,4 +1,3 @@
# needed to build the package setup_requires in setup.py
# do not unpin this (see setup.py)
setuptools_scm==1.15.6
setuptools-scm>=3.0.6
+2 -3
View File
@@ -1,10 +1,9 @@
# requirements for running the tests via pytest
pytest>=2.9
pytest>=2.9,<3.7 # <3.7 because of incompatible pluggy requirement
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
+2 -2
View File
@@ -1,5 +1,5 @@
# requirements for building and running tox
tox>=2.9.1,<3.0.0
detox>=0.11
tox>=3.1.2
tox-battery>=0.5
-r setup.txt
+1 -1
View File
@@ -1 +1 @@
python-3.6.4
python-3.6.6
+3
View File
@@ -1,2 +1,5 @@
[bdist_wheel]
universal = 1
[metadata]
license_file = LICENSE.rst
Regular → Executable
+60 -82
View File
@@ -1,10 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import distutils.core
from __future__ import print_function
import io
import os
import random
import string
import sys
from setuptools import find_packages, setup
@@ -22,88 +21,67 @@ requirements_setup = read_req('setup.txt')
requirements_validation = read_req('validation.txt')
def _install_setup_requires(attrs):
# copied from setuptools
dist = distutils.core.Distribution(dict(
(k, v) for k, v in attrs.items()
if k in ('dependency_links', 'setup_requires')
))
# Honor setup.cfg's options.
dist.parse_config_files(ignore_option_errors=True)
if dist.setup_requires:
dist.fetch_build_eggs(dist.setup_requires)
def drf_yasg_setup(**kwargs):
setup(
name='drf-yasg',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
install_requires=requirements,
setup_requires=requirements_setup,
extras_require={
'validation': requirements_validation,
},
license='BSD License',
description='Automated generation of real Swagger/OpenAPI 2.0 schemas from Django Rest Framework code.',
long_description=description,
url='https://github.com/axnsan12/drf-yasg',
author='Cristi V.',
author_email='cristi@cvjd.me',
keywords='drf django django-rest-framework schema swagger openapi codegen swagger-codegen '
'documentation drf-yasg django-rest-swagger drf-openapi',
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Topic :: Documentation',
'Topic :: Software Development :: Code Generators',
],
**kwargs
)
try:
# try to install setuptools_scm before setuptools does it, otherwise our monkey patch below will come too early
# (setuptools_scm adds find_files hooks into setuptools on install)
_install_setup_requires({'setup_requires': requirements_setup})
except Exception:
pass
if 'sdist' in sys.argv:
try:
# see https://github.com/pypa/setuptools_scm/issues/190, setuptools_scm includes ALL versioned files from
# the git repo into the sdist by default, and there is no easy way to provide an opt-out;
# this hack is ugly but does the job; because this is not really a documented interface of the module,
# the setuptools_scm version should remain pinned to ensure it keeps working
import setuptools_scm.integration
setuptools_scm.integration.find_files = lambda _: []
except ImportError:
pass
try:
# this is a workaround for being able to install the package from source without working from a git checkout
# it is needed for building succesfully on Heroku
from setuptools_scm import get_version
version = get_version()
version_kwargs = {'use_scm_version': True}
except LookupError:
if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
drf_yasg_setup(use_scm_version=True)
except LookupError as e:
if os.getenv('CI', 'false') == 'true' or os.getenv('TRAVIS', 'false') == 'true':
# don't silently fail on travis - we don't want to accidentally push a dummy version to PyPI
raise
rnd = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
version_kwargs = {'version': '0.0.0.dummy+' + rnd}
if 'setuptools-scm' in str(e):
import time
setup(
name='drf-yasg',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
install_requires=requirements,
setup_requires=requirements_setup,
extras_require={
'validation': requirements_validation,
},
license='BSD License',
description='Automated generation of real Swagger/OpenAPI 2.0 schemas from Django Rest Framework code.',
long_description=description,
url='https://github.com/axnsan12/drf-yasg',
author='Cristi V.',
author_email='cristi@cvjd.me',
keywords='drf django django-rest-framework schema swagger openapi codegen swagger-codegen '
'documentation drf-yasg django-rest-swagger drf-openapi',
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Topic :: Documentation',
'Topic :: Software Development :: Code Generators',
],
**version_kwargs
)
timestamp_ms = int(time.time() * 1000)
timestamp_str = hex(timestamp_ms)[2:].zfill(16)
dummy_version = '0.0.0rc0+noscm' + timestamp_str
drf_yasg_setup(version=dummy_version)
print(str(e), file=sys.stderr)
print("failed to detect version, build was done using dummy version " + dummy_version, file=sys.stderr)
else:
raise
+6
View File
@@ -2,6 +2,7 @@ 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': [
@@ -13,6 +14,7 @@ SWAGGER_DEFAULTS = {
'drf_yasg.inspectors.DictFieldInspector',
'drf_yasg.inspectors.HiddenFieldInspector',
'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.SerializerMethodFieldInspector',
'drf_yasg.inspectors.SimpleFieldInspector',
'drf_yasg.inspectors.StringDefaultFieldInspector',
],
@@ -24,6 +26,8 @@ SWAGGER_DEFAULTS = {
'drf_yasg.inspectors.CoreAPICompatInspector',
],
'EXCLUDED_MEDIA_TYPES': ['html'],
'DEFAULT_INFO': None,
'DEFAULT_API_URL': None,
@@ -45,6 +49,7 @@ 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': [
@@ -67,6 +72,7 @@ REDOC_DEFAULTS = {
}
IMPORT_STRINGS = [
'DEFAULT_GENERATOR_CLASS',
'DEFAULT_AUTO_SCHEMA_CLASS',
'DEFAULT_FIELD_INSPECTORS',
'DEFAULT_FILTER_INSPECTORS',
+42 -19
View File
@@ -5,7 +5,6 @@ from collections import OrderedDict, defaultdict
import uritemplate
from coreapi.compat import urlparse
from django.utils.encoding import force_text
from rest_framework import versioning
from rest_framework.compat import URLPattern, URLResolver, get_original_route
from rest_framework.schemas.generators import EndpointEnumerator as _EndpointEnumerator
@@ -18,7 +17,7 @@ from .app_settings import swagger_settings
from .errors import SwaggerGenerationError
from .inspectors.field import get_basic_type_info, get_queryset_field
from .openapi import ReferenceResolver
from .utils import get_consumes, get_produces
from .utils import force_real_str, get_consumes, get_produces
logger = logging.getLogger(__name__)
@@ -32,8 +31,7 @@ class EndpointEnumerator(_EndpointEnumerator):
def get_path_from_regex(self, path_regex):
if path_regex.endswith(')'):
logger.warning("url pattern does not end in $ ('%s') - unexpected things might happen",
path_regex)
logger.warning("url pattern does not end in $ ('%s') - unexpected things might happen", path_regex)
return self.unescape_path(super(EndpointEnumerator, self).get_path_from_regex(path_regex))
def should_include_endpoint(self, path, callback, app_name='', namespace='', url_name=None):
@@ -72,7 +70,7 @@ class EndpointEnumerator(_EndpointEnumerator):
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, ignored_endpoints=None):
"""
Return a list of all available API endpoints by inspecting the URL conf.
@@ -82,25 +80,38 @@ class EndpointEnumerator(_EndpointEnumerator):
patterns = self.patterns
api_endpoints = []
if ignored_endpoints is None:
ignored_endpoints = set()
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)
# avoid adding endpoints that have already been seen,
# as Django resolves urls in top-down order
if path in ignored_endpoints:
continue
ignored_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):
nested_endpoints = self.get_api_endpoints(
patterns=pattern.url_patterns,
prefix=path_regex,
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,
ignored_endpoints=ignored_endpoints
)
api_endpoints.extend(nested_endpoints)
else:
@@ -204,9 +215,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:
@@ -234,6 +251,8 @@ class OpenAPISchemaGenerator(object):
view_method = getattr(view, method, None)
if view_method is not None: # pragma: no cover
setattr(view_method.__func__, '_swagger_auto_schema', overrides)
setattr(view, 'swagger_fake_view', True)
return view
def get_endpoints(self, request):
@@ -315,7 +334,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 +377,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,7 +425,6 @@ class OpenAPISchemaGenerator(object):
"""
parameters = []
queryset = getattr(view_cls, 'queryset', None)
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
for variable in sorted(uritemplate.variables(path)):
model, model_field = get_queryset_field(queryset, variable)
@@ -410,7 +433,7 @@ class OpenAPISchemaGenerator(object):
attrs['pattern'] = getattr(view_cls, 'lookup_value_regex', attrs.get('pattern', None))
if model_field and getattr(model_field, 'help_text', False):
description = force_text(model_field.help_text)
description = model_field.help_text
elif model_field and getattr(model_field, 'primary_key', False):
description = get_pk_description(model, model_field)
else:
@@ -418,7 +441,7 @@ class OpenAPISchemaGenerator(object):
field = openapi.Parameter(
name=variable,
description=description,
description=force_real_str(description),
required=True,
in_=openapi.IN_PATH,
**attrs
+3 -3
View File
@@ -5,12 +5,12 @@ from .base import (
from .field import (
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector,
InlineSerializerInspector, RecursiveFieldInspector, ReferencingSerializerInspector, RelatedFieldInspector,
SimpleFieldInspector, StringDefaultFieldInspector
SerializerMethodFieldInspector, SimpleFieldInspector, StringDefaultFieldInspector
)
from .query import CoreAPICompatInspector, DjangoRestResponsePagination
from .view import SwaggerAutoSchema
# these settings must be accesed only after definig/importing all the classes in this module to avoid ImportErrors
# these settings must be accessed only after defining/importing all the classes in this module to avoid ImportErrors
ViewInspector.field_inspectors = swagger_settings.DEFAULT_FIELD_INSPECTORS
ViewInspector.filter_inspectors = swagger_settings.DEFAULT_FILTER_INSPECTORS
ViewInspector.paginator_inspectors = swagger_settings.DEFAULT_PAGINATOR_INSPECTORS
@@ -25,7 +25,7 @@ __all__ = [
# field inspectors
'InlineSerializerInspector', 'RecursiveFieldInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector',
'SimpleFieldInspector', 'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector',
'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector',
'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector', 'SerializerMethodFieldInspector',
# view inspectors
'SwaggerAutoSchema',
+36 -39
View File
@@ -1,12 +1,10 @@
import inspect
import logging
from django.utils.encoding import force_text
from rest_framework import serializers
from rest_framework.utils import encoders, json
from .. import openapi
from ..utils import decimal_as_float, is_list_view
from ..utils import force_real_str, get_field_default, is_list_view
#: Sentinel value that inspectors must return to signal that they do not know how to handle an object
NotHandled = object()
@@ -136,6 +134,19 @@ class FieldInspector(BaseInspector):
super(FieldInspector, self).__init__(view, path, method, components, request)
self.field_inspectors = field_inspectors
def add_manual_fields(self, serializer_or_field, schema):
"""Set fields from the ``swagger_schem_fields`` attribute on the Meta class. This method is called
only for serializers or fields that are converted into ``openapi.Schema`` objects.
:param serializer_or_field: serializer or field instance
:param openapi.Schema schema: the schema object to be modified in-place
"""
meta = getattr(serializer_or_field, 'Meta', None)
swagger_schema_fields = getattr(meta, 'swagger_schema_fields', {})
if swagger_schema_fields:
for attr, val in swagger_schema_fields.items():
setattr(schema, attr, val)
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
"""Convert a drf Serializer or Field instance into a Swagger object.
@@ -196,9 +207,9 @@ class FieldInspector(BaseInspector):
"""
assert swagger_object_type in (openapi.Schema, openapi.Parameter, openapi.Items)
assert not isinstance(field, openapi.SwaggerDict), "passed field is already a SwaggerDict object"
title = force_text(field.label) if field.label else None
title = force_real_str(field.label) if field.label else None
title = title if swagger_object_type == openapi.Schema else None # only Schema has title
description = force_text(field.help_text) if field.help_text else None
description = force_real_str(field.help_text) if field.help_text else None
description = description if swagger_object_type != openapi.Items else None # Items has no description either
def SwaggerType(existing_object=None, **instance_kwargs):
@@ -206,46 +217,29 @@ class FieldInspector(BaseInspector):
instance_kwargs['required'] = field.required
if 'default' not in instance_kwargs and swagger_object_type != openapi.Items:
default = getattr(field, 'default', serializers.empty)
if default is not serializers.empty:
if callable(default):
try:
if hasattr(default, 'set_context'):
default.set_context(field)
default = default()
except Exception: # pragma: no cover
logger.warning("default for %s is callable but it raised an exception when "
"called; 'default' field will not be added to schema", field, exc_info=True)
default = None
if default is not None:
try:
default = field.to_representation(default)
# JSON roundtrip ensures that the value is valid JSON;
# for example, sets and tuples get transformed into lists
default = json.loads(json.dumps(default, cls=encoders.JSONEncoder))
if decimal_as_float(field):
default = float(default)
except Exception: # pragma: no cover
logger.warning("'default' on schema for %s will not be set because "
"to_representation raised an exception", field, exc_info=True)
default = None
if default is not None:
instance_kwargs['default'] = default
default = get_field_default(field)
if default not in (None, serializers.empty):
instance_kwargs['default'] = default
if instance_kwargs.get('type', None) != openapi.TYPE_ARRAY:
instance_kwargs.setdefault('title', title)
instance_kwargs.setdefault('description', description)
if description is not None:
instance_kwargs.setdefault('description', description)
instance_kwargs.update(kwargs)
if existing_object is not None:
assert isinstance(existing_object, swagger_object_type)
for attr, val in sorted(instance_kwargs.items()):
setattr(existing_object, attr, val)
return existing_object
for key, val in sorted(instance_kwargs.items()):
setattr(existing_object, key, val)
result = existing_object
else:
result = swagger_object_type(**instance_kwargs)
return swagger_object_type(**instance_kwargs)
# Provide an option to add manual paremeters to a schema
# for example, to add examples
if swagger_object_type == openapi.Schema:
self.add_manual_fields(field, result)
return result
# arrays in Schema have Schema elements, arrays in Parameter and Items have Items elements
child_swagger_type = openapi.Schema if swagger_object_type == openapi.Schema else openapi.Items
@@ -276,7 +270,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 = [] #:
@@ -368,7 +365,7 @@ class ViewInspector(BaseInspector):
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
:returns: the converted :class:`.Schema`, or ``None`` in case of an unknown serializer
:rtype: openapi.Schema,openapi.SchemaRef,None
:rtype: openapi.Schema,openapi.SchemaRef
"""
return self.probe_inspectors(
self.field_inspectors, 'get_schema', serializer, {'field_inspectors': self.field_inspectors}
+163 -12
View File
@@ -1,5 +1,8 @@
import datetime
import inspect
import logging
import operator
import uuid
from collections import OrderedDict
from decimal import Decimal
@@ -10,9 +13,15 @@ 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, get_serializer_ref_name
from ..utils import decimal_as_float, filter_none, get_serializer_class, get_serializer_ref_name
from .base import FieldInspector, NotHandled, SerializerInspector
try:
# Python>=3.5
import typing
except ImportError:
typing = None
logger = logging.getLogger(__name__)
@@ -25,9 +34,20 @@ class InlineSerializerInspector(SerializerInspector):
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 +56,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,7 +80,7 @@ class InlineSerializerInspector(SerializerInspector):
if swagger_object_type != openapi.Schema:
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():
properties = OrderedDict()
@@ -63,14 +88,16 @@ class InlineSerializerInspector(SerializerInspector):
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(
@@ -80,16 +107,23 @@ class InlineSerializerInspector(SerializerInspector):
)
if not ref_name and 'title' in result:
# on an inline model, the title is derived from the field name
# but is visually displayed like the model name, which is confusing
# but is visno coverually displayed like the model name, which is confusing
# it is better to just remove title from inline models
del result.title
return result
if not ref_name or not use_references:
return make_schema_definition()
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
definitions.setdefault(ref_name, make_schema_definition)
actual_schema = definitions.setdefault(ref_name, make_schema_definition)
actual_serializer = get_serializer_class(getattr(actual_schema, '_serializer', None))
this_serializer = get_serializer_class(field)
if actual_serializer and actual_serializer != this_serializer: # pragma: no cover
logger.warning("Schema for %s will override distinct serializer %s because they "
"share the same ref_name", actual_serializer, this_serializer)
return openapi.SchemaRef(definitions, ref_name)
return NotHandled
@@ -281,6 +315,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()))
@@ -370,6 +408,118 @@ def get_basic_type_info(field):
return result
def decimal_return_type():
return openapi.TYPE_STRING if rest_framework_settings.COERCE_DECIMAL_TO_STRING else openapi.TYPE_NUMBER
raw_type_info = [
(bool, (openapi.TYPE_BOOLEAN, None)),
(int, (openapi.TYPE_INTEGER, None)),
(float, (openapi.TYPE_NUMBER, None)),
(Decimal, (decimal_return_type, openapi.FORMAT_DECIMAL)),
(uuid.UUID, (openapi.TYPE_STRING, openapi.FORMAT_UUID)),
(datetime.datetime, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
(datetime.date, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
# TODO - support typing.List etc
]
hinting_type_info = raw_type_info
def get_basic_type_info_from_hint(hint_class):
"""Given a class (eg from a SerializerMethodField's return type hint,
return its basic type information - ``type``, ``format``, ``pattern``,
and any applicable min/max limit values.
:param hint_class: the class
:return: the extracted attributes as a dictionary, or ``None`` if the field type is not known
:rtype: OrderedDict
"""
for check_class, type_format in hinting_type_info:
if issubclass(hint_class, check_class):
swagger_type, format = type_format
if callable(swagger_type):
swagger_type = swagger_type()
# if callable(format):
# format = format(klass)
break
else: # pragma: no cover
return None
pattern = None
result = OrderedDict([
('type', swagger_type),
('format', format),
('pattern', pattern)
])
return result
class SerializerMethodFieldInspector(FieldInspector):
"""Provides conversion for SerializerMethodField, optionally using information from the swagger_serializer_method
decorator.
"""
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
if not isinstance(field, serializers.SerializerMethodField):
return NotHandled
method = getattr(field.parent, field.method_name)
if method is None:
return NotHandled
serializer = getattr(method, "_swagger_serializer", None)
if serializer:
# attribute added by the swagger_serializer_method decorator
serializer = getattr(method, '_swagger_serializer', None)
# in order of preference for description, use:
# 1) field.help_text from SerializerMethodField(help_text)
# 2) serializer.help_text from swagger_serializer_method(serializer)
# 3) method's docstring
description = field.help_text
if description is None:
description = getattr(serializer, 'help_text', None)
if description is None:
description = method.__doc__
label = field.label
if label is None:
label = getattr(serializer, 'label', None)
if inspect.isclass(serializer):
serializer_kwargs = {
"help_text": description,
"label": label,
"read_only": True,
}
serializer = method._swagger_serializer(**serializer_kwargs)
else:
serializer.help_text = description
serializer.label = label
serializer.read_only = True
return self.probe_field_inspectors(serializer, swagger_object_type, use_references, read_only=True)
elif typing:
# look for Python 3.5+ style type hinting of the return value
hint_class = inspect.signature(method).return_annotation
if not issubclass(hint_class, inspect._empty):
type_info = get_basic_type_info_from_hint(hint_class)
if type_info is not None:
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type,
use_references, **kwargs)
return SwaggerType(**type_info)
return NotHandled
class SimpleFieldInspector(FieldInspector):
"""Provides conversions for fields which can be described using just ``type``, ``format``, ``pattern``
and min/max validators.
@@ -523,21 +673,22 @@ else:
try:
from rest_framework_recursive.fields import RecursiveField
except ImportError:
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"
assert ref_name is not None, "Can't create RecursiveField schema for inline " + str(type(field.proxied))
return openapi.SchemaRef(self.components.with_scope(openapi.SCHEMA_DEFINITIONS), ref_name,
ignore_unresolved=True)
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
return openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)
return NotHandled
+7 -2
View File
@@ -3,6 +3,8 @@ from collections import OrderedDict
import coreschema
from rest_framework.pagination import CursorPagination, LimitOffsetPagination, PageNumberPagination
from drf_yasg.utils import force_real_str
from .. import openapi
from .base import FilterInspector, PaginatorInspector
@@ -48,7 +50,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=force_real_str(field.schema.description) if field.schema else None,
)
@@ -70,7 +72,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
+63 -12
View File
@@ -1,3 +1,4 @@
import logging
from collections import OrderedDict
from rest_framework.request import is_form_media_type
@@ -7,11 +8,13 @@ from rest_framework.status import is_success
from .. import openapi
from ..errors import SwaggerGenerationError
from ..utils import (
force_serializer_instance, get_consumes, get_produces, guess_response_status, is_list_view, no_body,
force_real_str, force_serializer_instance, get_consumes, get_produces, guess_response_status, is_list_view, no_body,
param_list_to_odict
)
from .base import ViewInspector
log = logging.getLogger(__name__)
class SwaggerAutoSchema(ViewInspector):
def __init__(self, view, path, method, components, request, overrides):
@@ -31,21 +34,25 @@ class SwaggerAutoSchema(ViewInspector):
operation_id = self.get_operation_id(operation_keys)
description = self.get_description()
summary = self.get_summary()
security = self.get_security()
assert security is None or isinstance(security, list), "security must be a list of securiy requirement objects"
deprecated = self.is_deprecated()
tags = self.get_tags(operation_keys)
responses = self.get_responses()
return openapi.Operation(
operation_id=operation_id,
description=description,
description=force_real_str(description),
summary=force_real_str(summary),
responses=responses,
parameters=parameters,
consumes=consumes,
produces=produces,
tags=tags,
security=security
security=security,
deprecated=deprecated
)
def get_request_body_parameters(self, consumes):
@@ -83,12 +90,17 @@ 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 %s %s)",
self.method, self.path, 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.
def _get_request_body_override(self):
"""Parse the request_body key in the override dict. This method is not public API.
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
:return:
"""
body_override = self.overrides.get('request_body', None)
@@ -101,10 +113,20 @@ 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:
return body_override
def get_request_serializer(self):
"""Return the request serializer (used for parsing the request payload) for this endpoint.
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
"""
body_override = self._get_request_body_override()
if body_override is None and self.method in self.implicit_body_methods:
return self.get_view_serializer()
return None
return body_override
def get_request_form_parameters(self, serializer):
"""Given a Serializer, return a list of ``in: formData`` :class:`.Parameter`\ s.
@@ -144,8 +166,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())
@@ -161,6 +186,14 @@ class SwaggerAutoSchema(ViewInspector):
responses=self.get_response_schemas(response_serializers)
)
def get_default_response_serializer(self):
"""Return the default response serializer for this endpoint. This is derived from either the ``request_body``
override or the request serializer (:meth:`.get_view_serializer`).
:return: response serializer, :class:`.Schema`, :class:`.SchemaRef`, ``None``
"""
return self._get_request_body_override() or self.get_view_serializer()
def get_default_responses(self):
"""Get the default responses determined for this view from the request serializer and request method.
@@ -171,7 +204,7 @@ class SwaggerAutoSchema(ViewInspector):
default_status = guess_response_status(method)
default_schema = ''
if method in ('get', 'post', 'put', 'patch'):
default_schema = self.get_request_serializer() or self.get_view_serializer()
default_schema = self.get_default_response_serializer()
default_schema = default_schema or ''
if any(is_form_media_type(encoding) for encoding in self.get_consumes()):
@@ -217,8 +250,10 @@ class SwaggerAutoSchema(ViewInspector):
for sc, serializer in response_serializers.items():
if isinstance(serializer, str):
response = openapi.Response(
description=serializer
description=force_real_str(serializer)
)
elif not serializer:
continue
elif isinstance(serializer, openapi.Response):
response = serializer
if hasattr(response, 'schema') and not isinstance(response.schema, openapi.Schema.OR_REF):
@@ -294,6 +329,14 @@ class SwaggerAutoSchema(ViewInspector):
description = self._sch.get_description(self.path, self.method)
return description
def get_summary(self):
"""Return a summary description for this operation.
:return: the summary
:rtype: str
"""
return self.overrides.get('operation_summary', None)
def get_security(self):
"""Return a list of security requirements for this operation.
@@ -304,6 +347,14 @@ class SwaggerAutoSchema(ViewInspector):
:rtype: list[dict[str,list[str]]]"""
return self.overrides.get('security', None)
def is_deprecated(self):
"""Return ``True`` if this operation is to be marked as deprecated.
:return: deprecation status
:rtype: bool
"""
return self.overrides.get('deprecated', None)
def get_tags(self, operation_keys):
"""Get a list of tags for this operation. Tags determine how operations relate with each other, and in the UI
each tag will show as a group containing the operations that use it.
@@ -2,8 +2,9 @@ import json
import logging
import os
from collections import OrderedDict
from importlib import import_module
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand
from rest_framework.test import APIRequestFactory, force_authenticate
@@ -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):
@@ -50,9 +59,13 @@ class Command(BaseCommand):
help='Use a mock request when generating the swagger schema. This is useful if your views or serializers'
'depend on context from a request in order to function.'
)
parser.add_argument(
'--api-version', dest='api_version',
type=str,
help='Version to use to generate schema. This option implies --mock-request.'
)
parser.add_argument(
'--user', dest='user',
default='',
help='Username of an existing user to use for mocked authentication. This option implies --mock-request.'
)
parser.add_argument(
@@ -64,6 +77,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 +107,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, api_version, user, private, generator_class_name,
*args, **kwargs):
# disable logs of WARNING and below
logging.disable(logging.WARNING)
@@ -107,19 +126,30 @@ class Command(BaseCommand):
api_url = api_url or swagger_settings.DEFAULT_API_URL
user = User.objects.get(username=user) if user else None
mock = mock or private or (user is not None)
if user:
# Only call get_user_model if --user was passed in order to
# avoid crashing if auth is not configured in the project
user = get_user_model().objects.get(username=user)
mock = mock or private or (user is not None) or (api_version is not None)
if mock and not api_url:
raise ImproperlyConfigured(
'--mock-request requires an API url; either provide '
'the --url argument or set the DEFAULT_API_URL setting'
)
request = self.get_mock_request(api_url, format, user) if mock else None
request = None
if mock:
request = self.get_mock_request(api_url, format, user)
generator = OpenAPISchemaGenerator(
if request and api_version:
request.version = api_version
generator_class = import_class(generator_class_name) or swagger_settings.DEFAULT_GENERATOR_CLASS
generator = generator_class(
info=info,
url=api_url
version=api_version,
url=api_url,
)
schema = generator.get_schema(request=request, public=not private)
+11 -3
View File
@@ -1,3 +1,4 @@
import logging
import re
from collections import OrderedDict
@@ -7,6 +8,8 @@ from inflection import camelize
from .utils import filter_none
logger = logging.getLogger(__name__)
TYPE_OBJECT = "object" #:
TYPE_STRING = "string" #:
TYPE_NUMBER = "number" #:
@@ -116,7 +119,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 +224,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
@@ -628,8 +631,13 @@ class ReferenceResolver(object):
ret = self.getdefault(name, None, scope)
if ret is None:
ret = maker()
value = self.getdefault(name, None, scope)
assert ret is not None, "maker returned None; referenced objects cannot be None/null"
self.set(name, ret, scope)
if value is None:
self.set(name, ret, scope)
elif value != ret:
logger.debug("during setdefault, maker for %s inserted a value and returned a different value", name)
ret = value
return ret
+10 -3
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,6 +99,7 @@ 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,
}
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
+117 -18
View File
@@ -3,12 +3,16 @@ import logging
from collections import OrderedDict
from django.db import models
from django.utils.encoding import force_text
from rest_framework import serializers, status
from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.request import is_form_media_type
from rest_framework.settings import api_settings as rest_framework_settings
from rest_framework.utils import encoders, json
from rest_framework.views import APIView
from drf_yasg.app_settings import swagger_settings
logger = logging.getLogger(__name__)
@@ -23,9 +27,9 @@ class unset(object):
def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_body=None, query_serializer=None,
manual_parameters=None, operation_id=None, operation_description=None, security=None,
responses=None, field_inspectors=None, filter_inspectors=None, paginator_inspectors=None,
**extra_overrides):
manual_parameters=None, operation_id=None, operation_description=None, operation_summary=None,
security=None, deprecated=None, responses=None, field_inspectors=None, filter_inspectors=None,
paginator_inspectors=None, **extra_overrides):
"""Decorate a view method to customize the :class:`.Operation` object generated from it.
`method` and `methods` are mutually exclusive and must only be present when decorating a view method that accepts
@@ -66,9 +70,11 @@ 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 str operation_summary: operation summary string
: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 bool deprecated: deprecation status for operation
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
keyed on response status code. If no success (``2xx``) response is given, one will automatically be
generated from the request body and http method. If any ``2xx`` response is given the automatic response is
@@ -76,6 +82,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
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
an empty description will be generated
* a ``Serializer`` class or instance will be converted into a :class:`.Schema` and treated as above
@@ -114,19 +122,22 @@ 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 an @action, it will have a bind_to_methods attribute
# if the method is an @action, it will have a bind_to_methods attribute, or a mapping attribute for drf>3.8
bind_to_methods = getattr(view_method, 'bind_to_methods', [])
mapping = getattr(view_method, 'mapping', {})
mapping_methods = [mth for mth, name in mapping.items() if name == view_method.__name__]
action_http_methods = bind_to_methods + mapping_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)
http_method_names = [m for m in getattr(view_cls, 'http_method_names', []) if hasattr(view_cls, m)]
api_view_http_methods = [m for m in getattr(view_cls, 'http_method_names', []) if hasattr(view_cls, m)]
available_methods = http_method_names + bind_to_methods
available_http_methods = api_view_http_methods + action_http_methods
existing_data = getattr(view_method, '_swagger_auto_schema', {})
_methods = methods
if methods or method:
assert available_methods or http_method_names, "`method` or `methods` can only be specified " \
"on @action or @api_view views"
assert available_http_methods, "`method` or `methods` can only be specified 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"
@@ -134,20 +145,20 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
_methods = [method.lower()]
else:
_methods = [mth.lower() for mth in methods]
assert all(mth in available_methods for mth in _methods), "http method not bound to view"
assert all(mth in available_http_methods for mth in _methods), "http method not bound to view"
assert not any(mth in existing_data for mth in _methods), "http method defined multiple times"
if available_methods:
if available_http_methods:
# action or api_view
assert bool(http_method_names) != bool(bind_to_methods), "this should never happen"
assert bool(api_view_http_methods) != bool(action_http_methods), "this should never happen"
if len(available_methods) > 1:
if len(available_http_methods) > 1:
assert _methods, \
"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
_methods = _methods or available_http_methods
assert not any(hasattr(getattr(view_cls, mth, None), '_swagger_auto_schema') for mth in _methods), \
"swagger_auto_schema applied twice to method"
@@ -167,6 +178,23 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
return decorator
def swagger_serializer_method(serializer_or_field):
"""
Decorates the method of a serializers.SerializerMethodField
to hint as to how Swagger should be generated for this field.
:param serializer_or_field: ``Serializer``/``Field`` class or instance
:return:
"""
def decorator(serializer_method):
# stash the serializer for SerializerMethodFieldInspector to find
serializer_method._swagger_serializer = serializer_or_field
return serializer_method
return decorator
def is_list_view(path, method, view):
"""Check if the given path/method appears to represent a list view (as opposed to a detail/instance view).
@@ -248,6 +276,7 @@ def force_serializer_instance(serializer):
:param serializer: serializer class or instance
:return: serializer instance
:rtype: serializers.BaseSerializer
"""
if inspect.isclass(serializer):
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
@@ -258,6 +287,26 @@ def force_serializer_instance(serializer):
return serializer
def get_serializer_class(serializer):
"""Given a ``Serializer`` class or intance, return the ``Serializer`` class. If `serializer` is not a ``Serializer``
class or instance, raises an assertion error.
:param serializer: serializer class or instance, or ``None``
:return: serializer class
:rtype: type[serializers.BaseSerializer]
"""
if serializer is None:
return None
if inspect.isclass(serializer):
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
return serializer
assert isinstance(serializer, serializers.BaseSerializer), \
"Serializer class or instance required, not %s" % type(serializer).__name__
return type(serializer)
def get_consumes(parser_classes):
"""Extract ``consumes`` MIME types from a list of parser classes.
@@ -281,7 +330,8 @@ def get_produces(renderer_classes):
:rtype: list[str]
"""
media_types = [renderer.media_type for renderer in renderer_classes or []]
media_types = [encoding for encoding in media_types if 'html' not in encoding]
media_types = [encoding for encoding in media_types
if not any(excluded in encoding for excluded in swagger_settings.EXCLUDED_MEDIA_TYPES)]
return media_types
@@ -302,18 +352,67 @@ 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
:return: Serializer's ``ref_name`` or ``None`` for inline serializer
:rtype: str
"""
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))
logger.debug("Forcing inline output for ModelSerializer named 'NestedSerializer':\n" + str(serializer))
ref_name = None
else:
ref_name = serializer_name
if ref_name.endswith('Serializer'):
ref_name = ref_name[:-len('Serializer')]
return ref_name
def force_real_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Force `s` into a ``str`` instance.
Fix for https://github.com/axnsan12/drf-yasg/issues/159
"""
if s is not None:
s = force_text(s, encoding, strings_only, errors)
if type(s) != str:
s = '' + s
return s
def get_field_default(field):
"""
Get the default value for a field, converted to a JSON-compatible value while properly handling callables.
:param field: field instance
:return: default value
"""
default = getattr(field, 'default', serializers.empty)
if default is not serializers.empty:
if callable(default):
try:
if hasattr(default, 'set_context'):
default.set_context(field)
default = default()
except Exception: # pragma: no cover
logger.warning("default for %s is callable but it raised an exception when "
"called; 'default' will not be set on schema", field, exc_info=True)
default = serializers.empty
if default is not serializers.empty:
try:
default = field.to_representation(default)
# JSON roundtrip ensures that the value is valid JSON;
# for example, sets and tuples get transformed into lists
default = json.loads(json.dumps(default, cls=encoders.JSONEncoder))
if decimal_as_float(field):
default = float(default)
except Exception: # pragma: no cover
logger.warning("'default' on schema for %s will not be set because "
"to_representation raised an exception", field, exc_info=True)
default = serializers.empty
return default
+1 -2
View File
@@ -11,7 +11,6 @@ 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, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
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,
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.
+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)
Regular → Executable
View File
@@ -0,0 +1,28 @@
# Generated by Django 2.1 on 2018-08-06 13:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('people', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='identity',
name='lastName',
field=models.CharField(help_text="<strong>Here's some HTML!</strong>", max_length=30, null=True),
),
migrations.RenameField(
model_name='identity',
old_name='firstName',
new_name='first_name',
),
migrations.RenameField(
model_name='identity',
old_name='lastName',
new_name='last_name',
),
]
+3 -2
View File
@@ -1,9 +1,10 @@
from django.db import models
from django.utils.safestring import mark_safe
class Identity(models.Model):
firstName = models.CharField(max_length=30, null=True)
lastName = models.CharField(max_length=30, null=True)
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True, help_text=mark_safe("<strong>Here's some HTML!</strong>"))
class Person(models.Model):
+22
View File
@@ -23,12 +23,34 @@ class ExampleProjectSerializer(serializers.Serializer):
ref_name = 'Project'
class UnixTimestampField(serializers.DateTimeField):
def to_representation(self, value):
""" Return epoch time for a datetime object or ``None``"""
from django.utils.dateformat import format
try:
return int(format(value, 'U'))
except (AttributeError, TypeError):
return None
def to_internal_value(self, value):
import datetime
return datetime.datetime.fromtimestamp(int(value))
class Meta:
swagger_schema_fields = {
'format': 'integer',
'title': 'Client date time suu',
'description': 'Date time in unix timestamp format',
}
class SnippetSerializer(serializers.Serializer):
"""SnippetSerializer classdoc
create: docstring for create from serializer classdoc
"""
id = serializers.IntegerField(read_only=True, help_text="id serializer help text")
created = UnixTimestampField(read_only=True)
owner = serializers.PrimaryKeyRelatedField(
queryset=get_user_model().objects.all(),
default=serializers.CurrentUserDefault(),
+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)
+12 -1
View File
@@ -94,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
+11
View File
@@ -1,3 +1,5 @@
from collections import OrderedDict
from django.utils import timezone
from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
@@ -26,6 +28,15 @@ 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):
+1 -1
View File
@@ -13,6 +13,6 @@ router.register(r'recursive', views.TodoRecursiveView)
urlpatterns = router.urls
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(), ),
]
+40 -2
View File
@@ -1,6 +1,8 @@
from rest_framework import viewsets
from rest_framework.generics import RetrieveAPIView
from drf_yasg.utils import swagger_auto_schema
from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
from .serializer import (
TodoAnotherSerializer, TodoRecursiveSerializer, TodoSerializer, TodoTreeSerializer, TodoYetAnotherSerializer
@@ -31,9 +33,45 @@ class NestedTodoView(RetrieveAPIView):
class TodoTreeView(viewsets.ReadOnlyModelViewSet):
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):
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)
@@ -0,0 +1,69 @@
import datetime
import decimal
import uuid
from rest_framework import serializers
class Unknown(object):
pass
class MethodFieldExampleSerializer(serializers.Serializer):
"""
Implementation of SerializerMethodField using type hinting for Python >= 3.5
"""
hinted_bool = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a bool")
def get_hinted_bool(self, obj) -> bool:
return True
hinted_int = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be an integer")
def get_hinted_int(self, obj) -> int:
return 1
hinted_float = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a number")
def get_hinted_float(self, obj) -> float:
return 1.0
hinted_decimal = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a decimal")
def get_hinted_decimal(self, obj) -> decimal.Decimal:
return decimal.Decimal(1)
hinted_datetime = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a datetime")
def get_hinted_datetime(self, obj) -> datetime.datetime:
return datetime.datetime.now()
hinted_date = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a date")
def get_hinted_date(self, obj) -> datetime.date:
return datetime.date.today()
hinted_uuid = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a uuid")
def get_hinted_uuid(self, obj) -> uuid.UUID:
return uuid.uuid4()
hinted_unknown = serializers.SerializerMethodField(
help_text="type hint is unknown, so is expected to fallback to string")
def get_hinted_unknown(self, obj) -> Unknown:
return Unknown()
non_hinted_number = serializers.SerializerMethodField(
help_text="No hint on the method, so this is expected to fallback to string")
def get_non_hinted_number(self, obj):
return 1.0
@@ -0,0 +1,82 @@
import datetime
import decimal
import uuid
from rest_framework import serializers
from drf_yasg.utils import swagger_serializer_method
class Unknown(object):
pass
class MethodFieldExampleSerializer(serializers.Serializer):
"""
Fallback implementation of SerializerMethodField type hinting for Python < 3.5
`->` syntax isn't supported, instead decorate with a serializer that returns the same type
a bit of a hack, but it provides a cross-check between hinting and decorator functionality.
"""
hinted_bool = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a bool")
@swagger_serializer_method(serializer_or_field=serializers.BooleanField)
def get_hinted_bool(self, obj):
return True
hinted_int = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be an integer")
@swagger_serializer_method(serializer_or_field=serializers.IntegerField)
def get_hinted_int(self, obj):
return 1
hinted_float = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a number")
@swagger_serializer_method(serializer_or_field=serializers.FloatField)
def get_hinted_float(self, obj):
return 1.0
hinted_decimal = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a decimal")
# note that in this case an instance is required since DecimalField has required arguments
@swagger_serializer_method(serializer_or_field=serializers.DecimalField(max_digits=6, decimal_places=4))
def get_hinted_decimal(self, obj):
return decimal.Decimal(1)
hinted_datetime = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a datetime")
@swagger_serializer_method(serializer_or_field=serializers.DateTimeField)
def get_hinted_datetime(self, obj):
return datetime.datetime.now()
hinted_date = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a date")
@swagger_serializer_method(serializer_or_field=serializers.DateField)
def get_hinted_date(self, obj):
return datetime.date.today()
hinted_uuid = serializers.SerializerMethodField(
help_text="the type hint on the method should determine this to be a uuid")
@swagger_serializer_method(serializer_or_field=serializers.UUIDField)
def get_hinted_uuid(self, obj):
return uuid.uuid4()
hinted_unknown = serializers.SerializerMethodField(
help_text="type hint is unknown, so is expected to fallback to string")
def get_hinted_unknown(self, obj):
return Unknown()
non_hinted_number = serializers.SerializerMethodField(
help_text="No hint on the method, so this is expected to fallback to string")
def get_non_hinted_number(self, obj):
return 1.0
+63 -1
View File
@@ -1,8 +1,19 @@
from django.contrib.auth.models import User
from rest_framework import serializers
from drf_yasg.utils import swagger_serializer_method
from snippets.models import Snippet
try:
import typing # noqa: F401
from .method_serializers_with_typing import MethodFieldExampleSerializer
except ImportError:
from .method_serializers_without_typing import MethodFieldExampleSerializer
class OtherStuffSerializer(serializers.Serializer):
foo = serializers.CharField()
class UserSerializerrr(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
@@ -10,10 +21,61 @@ class UserSerializerrr(serializers.ModelSerializer):
last_connected_ip = serializers.IPAddressField(help_text="i'm out of ideas", protocol='ipv4', read_only=True)
last_connected_at = serializers.DateField(help_text="really?", read_only=True)
other_stuff = serializers.SerializerMethodField(
help_text="the decorator should determine the serializer class for this")
hint_example = MethodFieldExampleSerializer()
@swagger_serializer_method(serializer_or_field=OtherStuffSerializer)
def get_other_stuff(self, obj):
"""
method_field that uses a serializer internally.
By using the decorator, we can tell drf-yasg how to represent this in Swagger
:param obj:
:return:
"""
return OtherStuffSerializer().data
help_text_example_1 = serializers.SerializerMethodField(
help_text="help text on field is set, so this should appear in swagger"
)
@swagger_serializer_method(serializer_or_field=serializers.IntegerField(
help_text="decorated instance help_text shouldn't appear in swagger because field has priority"))
def get_help_text_example_1(self):
"""
method docstring shouldn't appear in swagger because field has priority
:return:
"""
return 1
help_text_example_2 = serializers.SerializerMethodField()
@swagger_serializer_method(serializer_or_field=serializers.IntegerField(
help_text="instance help_text is set, so should appear in swagger"))
def get_help_text_example_2(self):
"""
method docstring shouldn't appear in swagger because decorator has priority
:return:
"""
return 1
help_text_example_3 = serializers.SerializerMethodField()
@swagger_serializer_method(serializer_or_field=serializers.IntegerField())
def get_help_text_example_3(self):
"""
docstring is set so should appear in swagger as fallback
:return:
"""
return 1
class Meta:
model = User
fields = ('id', 'username', 'email', 'articles', 'snippets',
'last_connected_ip', 'last_connected_at', 'article_slugs')
'last_connected_ip', 'last_connected_at', 'article_slugs', 'other_stuff', 'hint_example',
'help_text_example_1', 'help_text_example_2', 'help_text_example_3')
class UserListQuerySerializer(serializers.Serializer):
+18
View File
@@ -1,3 +1,5 @@
from six import StringIO
import copy
import json
import os
@@ -6,6 +8,7 @@ from collections import OrderedDict
import pytest
from datadiff.tools import assert_equal
from django.contrib.auth.models import User
from django.core.management import call_command
from rest_framework.test import APIRequestFactory
from rest_framework.views import APIView
@@ -64,6 +67,21 @@ def validate_schema(db):
return validate_schema
@pytest.fixture
def call_generate_swagger():
def call_generate_swagger(output_file='-', overwrite=False, format='', api_url='',
mock=False, user=None, 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, generator_class_name=generator_class_name, **kwargs
)
return out.getvalue()
return call_generate_swagger
@pytest.fixture
def compare_schemas():
def compare_schemas(schema1, schema2):
+156 -13
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
@@ -382,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:
@@ -436,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:
@@ -532,10 +560,8 @@ paths:
description: ''
parameters: []
responses:
'200':
description: ''
schema:
$ref: '#/definitions/TodoRecursive'
'302':
description: Redirect somewhere
tags:
- todo
put:
@@ -669,9 +695,9 @@ paths:
description: A unique integer value identifying this todo.
required: true
type: integer
/todo/{todo_id}/yetanother/{yetanother_id}/:
/todo/{todo_id}/yetanothers/{yetanother_id}/:
get:
operationId: todo_yetanother_read
operationId: todo_yetanothers_read
description: ''
parameters: []
responses:
@@ -700,6 +726,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!
@@ -800,6 +827,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.
@@ -809,6 +837,7 @@ definitions:
description: body serializer help_text
type: string
maxLength: 5000
minLength: 1
slug:
description: slug model help_text
type: string
@@ -830,6 +859,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?
@@ -868,14 +898,17 @@ definitions:
title: ID
type: integer
readOnly: true
firstName:
title: FirstName
first_name:
title: First name
type: string
maxLength: 30
lastName:
title: LastName
minLength: 1
last_name:
title: Last name
description: <strong>Here's some HTML!</strong>
type: string
maxLength: 30
minLength: 1
Person:
required:
- identity
@@ -897,10 +930,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
@@ -912,6 +947,12 @@ definitions:
description: id serializer help text
type: integer
readOnly: true
created:
title: Client date time suu
type: string
format: integer
readOnly: true
description: Date time in unix timestamp format
owner:
title: Owner
description: The ID of the user that created this snippet; if none is provided,
@@ -922,6 +963,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
@@ -930,6 +972,7 @@ definitions:
code:
title: Code
type: string
minLength: 1
linenos:
title: Linenos
type: boolean
@@ -1448,6 +1491,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
TodoAnother:
required:
- title
@@ -1458,6 +1502,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
todo:
$ref: '#/definitions/Todo'
TodoRecursive:
@@ -1473,6 +1518,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
parent:
$ref: '#/definitions/TodoRecursive'
parent_id:
@@ -1492,6 +1538,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
children:
type: array
items:
@@ -1505,6 +1552,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
todo:
required:
- title
@@ -1518,6 +1566,7 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
todo:
required:
- title
@@ -1531,13 +1580,85 @@ definitions:
title: Title
type: string
maxLength: 50
minLength: 1
readOnly: true
readOnly: true
example:
title: parent
todo:
title: child
todo: null
OtherStuff:
title: Other stuff
description: the decorator should determine the serializer class for this
required:
- foo
type: object
properties:
foo:
title: Foo
type: string
minLength: 1
readOnly: true
MethodFieldExample:
title: Hint example
type: object
properties:
hinted_bool:
title: Hinted bool
description: the type hint on the method should determine this to be a bool
type: boolean
readOnly: true
hinted_int:
title: Hinted int
description: the type hint on the method should determine this to be an integer
type: integer
readOnly: true
hinted_float:
title: Hinted float
description: the type hint on the method should determine this to be a number
type: number
readOnly: true
hinted_decimal:
title: Hinted decimal
description: the type hint on the method should determine this to be a decimal
type: string
format: decimal
readOnly: true
hinted_datetime:
title: Hinted datetime
description: the type hint on the method should determine this to be a datetime
type: string
format: date-time
readOnly: true
hinted_date:
title: Hinted date
description: the type hint on the method should determine this to be a date
type: string
format: date
readOnly: true
hinted_uuid:
title: Hinted uuid
description: the type hint on the method should determine this to be a uuid
type: string
format: uuid
readOnly: true
hinted_unknown:
title: Hinted unknown
description: type hint is unknown, so is expected to fallback to string
type: string
readOnly: true
non_hinted_number:
title: Non hinted number
description: No hint on the method, so this is expected to fallback to string
type: string
readOnly: true
UserSerializerrr:
required:
- username
- articles
- snippets
- hint_example
type: object
properties:
id:
@@ -1551,6 +1672,7 @@ definitions:
type: string
pattern: ^[\w.@+-]+$
maxLength: 150
minLength: 1
email:
title: Email address
type: string
@@ -1572,6 +1694,7 @@ definitions:
type: string
format: ipv4
readOnly: true
minLength: 1
last_connected_at:
title: Last connected at
description: really?
@@ -1586,3 +1709,23 @@ definitions:
pattern: ^[-a-zA-Z0-9_]+$
readOnly: true
uniqueItems: true
other_stuff:
$ref: '#/definitions/OtherStuff'
hint_example:
$ref: '#/definitions/MethodFieldExample'
help_text_example_1:
title: Help text example 1
description: help text on field is set, so this should appear in swagger
type: integer
readOnly: true
help_text_example_2:
title: Help text example 2
description: instance help_text is set, so should appear in swagger
type: integer
readOnly: true
help_text_example_3:
title: Help text example 3
description: "\n docstring is set so should appear in swagger as fallback\n\
\ :return:\n "
type: integer
readOnly: true
+17 -19
View File
@@ -1,5 +1,3 @@
from six import StringIO
import json
import os
import random
@@ -9,24 +7,13 @@ from collections import OrderedDict
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):
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
)
return out.getvalue()
def test_reference_schema(db, reference_schema):
def test_reference_schema(call_generate_swagger, db, reference_schema):
User.objects.create_superuser('admin', 'admin@admin.admin', 'blabla')
output = call_generate_swagger(format='yaml', api_url='http://test.local:8002/', user='admin')
@@ -34,18 +21,29 @@ def test_reference_schema(db, reference_schema):
assert output_schema == reference_schema
def test_non_public(db):
def test_non_public(call_generate_swagger, db):
output = call_generate_swagger(format='yaml', api_url='http://test.local:8002/', private=True)
output_schema = yaml_sane_load(output)
assert len(output_schema['paths']) == 0
def test_no_mock(db):
def test_no_mock(call_generate_swagger, db):
output = call_generate_swagger()
output_schema = json.loads(output, object_pairs_hook=OrderedDict)
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(call_generate_swagger, 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)
@@ -53,7 +51,7 @@ def silentremove(filename):
pass
def test_file_output(db):
def test_file_output(call_generate_swagger, db):
prefix = os.path.join(tempfile.gettempdir(), tempfile.gettempprefix())
name = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
yaml_file = prefix + name + '.yaml'
+77
View File
@@ -2,7 +2,9 @@ import json
from collections import OrderedDict
import pytest
from django.conf.urls import url
from rest_framework import routers, serializers, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from drf_yasg import codecs, openapi
@@ -113,3 +115,78 @@ def test_replaced_serializer():
responses = swagger['paths']['/details/{id}/']['get']['responses']
assert '404' in responses
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
try:
from rest_framework.decorators import action, MethodMapper
except ImportError:
action = MethodMapper = None
@pytest.mark.skipif(not MethodMapper or not action, reason="action.mapping test (djangorestframework>=3.9 required)")
def test_action_mapping():
class ActionViewSet(viewsets.ViewSet):
@swagger_auto_schema(method='get', operation_id='mapping_get')
@swagger_auto_schema(method='delete', operation_id='mapping_delete')
@action(detail=False, methods=['get', 'delete'], url_path='test')
def action_main(self, request):
"""mapping docstring get/delete"""
pass
@swagger_auto_schema(operation_id='mapping_post')
@action_main.mapping.post
def action_post(self, request):
"""mapping docstring post"""
pass
router = routers.DefaultRouter()
router.register(r'action', ActionViewSet, base_name='action')
generator = OpenAPISchemaGenerator(
info=openapi.Info(title="Test generator", default_version="v1"),
version="v2",
url='',
patterns=router.urls
)
for _ in range(3):
swagger = generator.get_schema(None, True)
action_ops = swagger['paths']['/test/']
methods = ['get', 'post', 'delete']
assert all(mth in action_ops for mth in methods)
assert all(action_ops[mth]['operationId'] == 'mapping_' + mth for mth in methods)
assert action_ops['post']['description'] == 'mapping docstring post'
assert action_ops['get']['description'] == 'mapping docstring get/delete'
assert action_ops['delete']['description'] == 'mapping docstring get/delete'
+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())
+26
View File
@@ -7,6 +7,18 @@ def _get_versioned_schema(prefix, client, validate_schema):
response = client.get(prefix + '/swagger.yaml')
assert response.status_code == 200
swagger = yaml_sane_load(response.content.decode('utf-8'))
_check_base(swagger, prefix, validate_schema)
return swagger
def _get_versioned_schema_management(prefix, call_generate_swagger, validate_schema, kwargs):
output = call_generate_swagger(format='yaml', api_url='http://localhost' + prefix + '/swagger.yaml', **kwargs)
swagger = yaml_sane_load(output)
_check_base(swagger, prefix, validate_schema)
return swagger
def _check_base(swagger, prefix, validate_schema):
assert swagger['basePath'] == prefix
validate_schema(swagger)
assert '/snippets/' in swagger['paths']
@@ -51,3 +63,17 @@ def test_ns_v1(client, validate_schema):
def test_ns_v2(client, validate_schema):
swagger = _get_versioned_schema('/versioned/ns/v2.0', client, validate_schema)
_check_v2(swagger)
@pytest.mark.urls('urlconfs.url_versioning')
def test_url_v2_management(call_generate_swagger, validate_schema):
kwargs = {'api_version': '2.0'}
swagger = _get_versioned_schema_management('/versioned/url/v2.0', call_generate_swagger, validate_schema, kwargs)
_check_v2(swagger)
@pytest.mark.urls('urlconfs.ns_versioning')
def test_ns_v2_management(call_generate_swagger, validate_schema):
kwargs = {'api_version': '2.0'}
swagger = _get_versioned_schema_management('/versioned/ns/v2.0', call_generate_swagger, validate_schema, kwargs)
_check_v2(swagger)
+16 -13
View File
@@ -1,28 +1,29 @@
[tox]
# https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django
envlist =
py27-django111-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
py{27,34,35,36}-django111-drf37,
py{27,34,35,36}-django111-drf38,
py{34,35,36,37}-django20-drf37,
py{34,35,36,37}-django20-drf38,
py{35,36,37}-django21-drf37,
py{35,36,37}-django21-drf38,
djmaster, lint, docs
[testenv]
deps =
django111: Django>=1.11,<2.0
django20: Django>=2.0,<2.1
django21: Django>=2.1,<2.2
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
djmaster: https://github.com/encode/django-rest-framework/archive/master.tar.gz
djmaster: https://github.com/django/django/archive/master.tar.gz
# other dependencies
-rrequirements/setup.txt
-rrequirements/validation.txt
-rrequirements/test.txt
@@ -32,12 +33,14 @@ commands =
[testenv:lint]
skip_install = true
deps =
-rrequirements/setup.txt
-rrequirements/lint.txt
commands =
flake8 src/drf_yasg testproj tests setup.py
[testenv:docs]
deps =
-rrequirements/setup.txt
-rrequirements/docs.txt
commands =
python setup.py check --restructuredtext --metadata --strict
@@ -46,7 +49,7 @@ commands =
[pytest]
DJANGO_SETTINGS_MODULE = testproj.settings.local
python_paths = testproj
addopts = -n 3
addopts = -n 2 --ignore=node_modules
[flake8]
max-line-length = 120
@@ -54,7 +57,7 @@ exclude = **/migrations/*
ignore = F405
[isort]
skip = .eggs,.tox,docs,env,venv
skip = .eggs,.tox,docs,env,venv,node_modules
skip_glob = **/migrations/*
not_skip = __init__.py
atomic = true
Regular → Executable
View File