Compare commits

..

90 Commits

Author SHA1 Message Date
Cristi Vîjdea 161a2e1b89 Ignore schizophrenic flake8 error 2018-11-29 02:24:03 +02:00
Cristi Vîjdea a2bf515cc9 Revert "Fix lint errors"
This reverts commit 9f60dc191a.
2018-11-29 02:23:31 +02:00
Cristi Vîjdea 10a32f977c Add 1.11.1 changelog 2018-11-29 02:18:58 +02:00
Cristi Vîjdea 6b5022cd7d Use some more coreschema attributes in CoreAPICompatInspector
Closes #212.
Closes #233.
2018-11-29 02:12:32 +02:00
Cristi Vîjdea 708e70a526 Use collectionFormat=multi for MultiChoiceField in query and formData
Fixes #257.
2018-11-29 01:38:40 +02:00
Cristi Vîjdea 9f60dc191a Fix lint errors 2018-11-29 01:27:27 +02:00
Cristi Vîjdea a2b35f3363 Update swagger-ui to 3.20.1 and ReDoc to 2.0.0-alpha.41 2018-11-29 01:22:49 +02:00
Cristi Vîjdea 754ec8a779 Enable minLength and maxLength for ListSerializer 2018-11-29 00:32:31 +02:00
Randall Wang 3cd93bd572 Fix typo (#252) 2018-11-16 13:53:19 +02:00
Cristi Vîjdea c5f6a79cc8 Fix heroku build 2018-10-14 21:44:32 +03:00
Cristi Vîjdea 1ac85f6eba Release version 1.11.0 2018-10-14 21:35:07 +03:00
Cristi Vîjdea c2e4d7767b Update reference schema 2018-10-14 21:25:24 +03:00
Cristi Vîjdea baaa79a29d Fix IE11 bugs 2018-10-14 21:25:17 +03:00
Cristi Vîjdea 8dfab883a5 Add 1.11.0 changelog 2018-10-14 20:43:26 +03:00
Cristi Vîjdea dfe06b5c95 Copy window query params when fetching the openapi document
Closes #208.
2018-10-14 20:40:34 +03:00
Cristi Vîjdea 18ff51a025 Improve handling of spec request url 2018-10-14 20:23:53 +03:00
Cristi Vîjdea e1aedab73f Support multiple auth schemes 2018-10-14 18:16:09 +03:00
Cristi Vîjdea 060fe1881a Add auth hook settings and apiKey query support 2018-10-14 17:38:39 +03:00
Cristi Vîjdea 5d8c936956 Moar blocks 2018-10-14 05:23:45 +03:00
Cristi Vîjdea 25dea81bc6 Update swagger-ui to 3.19.3 and ReDoc to 2.0.0-alpha.40 2018-10-14 04:30:53 +03:00
Cristi Vîjdea a419eec071 Add swagger-ui auth hooks
Save authorization to local storage, refetch spec on auth, etc.
2018-10-14 04:28:42 +03:00
Rémi Lapeyre d41f0c5ac4 Set x-nullable based on allow_null (#217)
Many fields may be set a nullable in an API. While not covered explicitly by Swagger 2, this information is usually indicated as a [vendor extension](https://swagger.io/docs/specification/2-0/swagger-extensions/) using the x-nullable field.
2018-10-10 01:24:42 +03:00
Cristi Vîjdea c510de13d7 Do not try to use inspect.signature on Python 2.7
Fixes #222.
2018-10-10 00:35:43 +03:00
Cristi Vîjdea 207a7e2b2d Do not generate full schema in UI views 2018-10-09 01:38:12 +03:00
Cristi Vîjdea cbae10c434 Refactor CamelCaseJSONFilter to be more extensible 2018-10-09 01:37:32 +03:00
Cristi Vîjdea 81fa4b44c8 Remove setup requirements from lint tox env 2018-10-09 01:16:58 +03:00
Cristi Vîjdea 20786e53c3 Provide more OpenAPISchemaGenerator extension points
Add ``should_include_endpoint`` and ``get_paths_object``.
2018-09-13 05:51:34 +03:00
Cristi Vîjdea 120c4dd884 Fix IPv4 pattern on Django 1.11 2018-09-13 05:14:08 +03:00
Cristi Vîjdea 5bdce56bba Fix docs build with sphinx 1.8 2018-09-13 05:12:40 +03:00
Cristi Vîjdea e761e2da50 Add 1.10.2 changelog 2018-09-13 04:19:31 +03:00
Cristi Vîjdea 9d330d9509 Use the first line of view method docstring as Operation summary
Closes #205.
2018-09-13 04:18:55 +03:00
Cristi Vîjdea c8f6d16891 Update ReDoc to 2.0.0-alpha.38 2018-09-13 03:44:10 +03:00
Cristi Vîjdea 857ef05b07 Handle reverse_lazy
Fixes #209.
2018-09-13 03:38:13 +03:00
Cristi Vîjdea 586b88d8f3 Allow pattern on any field 2018-09-13 03:34:01 +03:00
Cristi Vîjdea 27cd5f7f2a Add some convenience methods 2018-09-11 02:41:55 +03:00
Cristi Vîjdea 90812f5c43 Refactor get_queryset_from_view 2018-09-10 14:34:30 +03:00
Cristi Vîjdea a6ae8b0521 Add ReDoc settings descriptions 2018-09-10 14:02:37 +03:00
Cristi Vîjdea 91530b64c6 Add DISPLAY_OPERATION_ID setting for swagger-ui
Closes #206.
2018-09-10 14:02:25 +03:00
Cristi Vîjdea 6820d6bc70 Fix RelatedFieldInspector nesting issues 2018-09-10 05:04:03 +03:00
Cristi Vîjdea f50ad29a2b Fix lint errors 2018-09-10 02:48:08 +03:00
Cristi Vîjdea 27e38101a4 Add customization blocks to ui templates
Closes #178.
2018-09-10 02:41:02 +03:00
Cristi Vîjdea 4bac38e67b Update ReDoc settings 2018-09-10 01:39:57 +03:00
Cristi Vîjdea 10abf46597 Merge pull request #204 from axnsan12/release-1.10.1
Lotsa fixes. Sorry for the long time no see 😄
2018-09-10 01:00:26 +03:00
Cristi Vîjdea 42841e3092 Add 1.10.1 changelog 2018-09-10 00:42:45 +03:00
Cristi Vîjdea 0654aefe58 Update swagger-ui to 3.18.2 and ReDoc to 2.0.0-alpha.37 2018-09-10 00:13:39 +03:00
Cristi Vîjdea 41b1ca4483 Do not bail on response when request body is formData 2018-09-10 00:02:39 +03:00
Cristi Vîjdea b109d4c847 Fix bad test for no_body 2018-09-09 23:14:09 +03:00
Cristi Vîjdea 591c12f1a7 Fix request_body=no_body handling
Fixes #188, #199.
2018-09-09 23:14:09 +03:00
Cristi Vîjdea 271918a678 Fix empty swagger_auto_schema return value 2018-09-09 23:14:09 +03:00
Cristi Vîjdea c5c40e31c4 Log regex compilation failure in find_regex
Closes #193.
2018-09-09 22:33:13 +03:00
Cristi Vîjdea 3ac6c9ec3a Remove dependency on future
Sole use was raise_from. 

six.raise_from loses exception detail on Python 2, so god help the programmers of the past.

Fixes #196.
2018-09-09 22:29:11 +03:00
Cristi Vîjdea 5fa35d5b81 Check for None before calling to_representation
Django REST Framework also does this in serializers.

https://github.com/encode/django-rest-framework/issues/2299
https://github.com/encode/django-rest-framework/blob/4d57d46bf89f54f276909219ee06f0a2bf112f9f/rest_framework/serializers.py#L518

Fixes #203.
2018-09-09 22:22:58 +03:00
Terence D. Honles f9b215deab Fix missing backslashes found via pytest 3.8 (#202)
See: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

Changed in version 3.6: Unrecognized escape sequences produce a DeprecationWarning

Closes #202.
2018-09-09 22:17:04 +03:00
Nour Chawich 0837873f55 Add missing overrides to swagger_auto_schema (#194)
Add missing `operation_summary` and `deprecated` to `swagger_auto_schema` decorator data. The previous PR missed adding these to extra overrides.

- Added tests
- Updated reference.yaml

Refs #149, #173.
Closes #194, #198.
2018-09-09 22:15:50 +03:00
Julian Bez 02b8848912 Fix error when using typing classes (#195)
Closes #195.
2018-09-09 22:11:29 +03:00
Cristi Vîjdea 6e39a58b2d Defer settings imports to avoid ImportErrors 2018-09-09 21:56:26 +03:00
Cristi Vîjdea e146a9712e Remove minor version from PyCharm python interpreter name
This allows for conflictless development on any supproted python version
2018-09-09 21:56:26 +03:00
Cristi Vîjdea ec7529399e Fix swagger-ui style when session auth is disabled 2018-09-09 21:56:26 +03:00
Cristi Vîjdea 824baf7e9d Update PyCharm interpreter to python 3.7 2018-08-14 09:54:05 +03:00
Cristi Vîjdea dd50eb5e12 Remove unused requirement 2018-08-14 09:53:47 +03:00
Cristi Vîjdea 9b56e1a4c8 Avoid invalid usage of readOnly 2018-08-09 04:27:08 +03:00
Cristi Vîjdea 608abaf0e1 Fuck this test 2018-08-09 04:02:35 +03:00
Cristi Vîjdea 64e13a94da Remove tox-battery from CI requirements 2018-08-09 03:54:35 +03:00
Cristi Vîjdea 5051f91c97 Don't cache .tox on travis 2018-08-09 03:52:18 +03:00
Cristi Vîjdea d1ae81a27e Fix relative imports 2018-08-09 03:52:09 +03:00
Cristi Vîjdea 1ca401959c Fix tests 2018-08-09 03:40:35 +03:00
Cristi Vîjdea cd4bd4a18e Add SPEC_URL setting 2018-08-09 03:32:04 +03:00
Cristi Vîjdea 8a69f08c29 Update ReDoc to 2.0.0-alpha.34 2018-08-09 03:15:08 +03:00
Cristi Vîjdea e533b0827a Add ReDoc 1.x.x renderer 2018-08-09 03:14:08 +03:00
Cristi Vîjdea dc78dfdad8 Shrink tox envlist 2018-08-08 01:53:24 +03:00
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
74 changed files with 2267 additions and 881 deletions
+2 -3
View File
@@ -1,7 +1,8 @@
node_modules/ node_modules/
testproj/db.sqlite3 testproj/db.sqlite3
testproj/staticfiles testproj/staticfiles
.vscode/ \.pytest_cache/
docs/\.doctrees/
# Created by .ignore support plugin (hsz.mobi) # Created by .ignore support plugin (hsz.mobi)
### Python template ### Python template
@@ -159,5 +160,3 @@ com_crashlytics_export_strings.xml
crashlytics.properties crashlytics.properties
crashlytics-build.properties crashlytics-build.properties
fabric.properties fabric.properties
\.pytest_cache/
+11 -3
View File
@@ -16,22 +16,30 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/testproj" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/testproj" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.pytest_cache" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
<excludeFolder url="file://$MODULE_DIR$/docs/.doctrees" />
<excludeFolder url="file://$MODULE_DIR$/docs/_build" /> <excludeFolder url="file://$MODULE_DIR$/docs/_build" />
<excludeFolder url="file://$MODULE_DIR$/htmlcov" />
<excludeFolder url="file://$MODULE_DIR$/src/drf_yasg.egg-info" />
<excludeFolder url="file://$MODULE_DIR$/venv" /> <excludeFolder url="file://$MODULE_DIR$/venv" />
</content> </content>
<orderEntry type="jdk" jdkName="Python 3.6 (drf-yasg)" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Python 3 (drf-yasg)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="immutable" level="application" />
</component> </component>
<component name="TemplatesService"> <component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" /> <option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS"> <option name="TEMPLATE_FOLDERS">
<list> <list>
<option value="$MODULE_DIR$/src/drf_yasg/templates" /> <option value="$MODULE_DIR$/src/drf_yasg/templates" />
<option value="$MODULE_DIR$/testproj/testproj/templates" />
</list> </list>
</option> </option>
</component> </component>
<component name="TestRunnerService"> <component name="TestRunnerService">
<option name="projectConfiguration" value="py.test" /> <option name="projectConfiguration" value="pytest" />
<option name="PROJECT_TEST_RUNNER" value="py.test" /> <option name="PROJECT_TEST_RUNNER" value="pytest" />
</component> </component>
</module> </module>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<file url="file://$PROJECT_DIR$" libraries="{immutable}" />
</component>
</project>
+1 -1
View File
@@ -69,7 +69,7 @@
<textMaps /> <textMaps />
</LinkMapSettings> </LinkMapSettings>
</component> </component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (drf-yasg)" project-jdk-type="Python SDK" /> <component name="ProjectRootManager" version="2" project-jdk-name="Python 3 (drf-yasg)" project-jdk-type="Python SDK" />
<component name="PythonCompatibilityInspectionAdvertiser"> <component name="PythonCompatibilityInspectionAdvertiser">
<option name="version" value="3" /> <option name="version" value="3" />
</component> </component>
+21 -25
View File
@@ -1,28 +1,28 @@
language: python language: python
cache: pip sudo: false
python: python:
- '3.4' - '2.7'
- '3.5' - '3.4'
- '3.6' - '3.5'
- '3.6'
env: cache: pip
- DRF=3.7
- DRF=3.8
jobs: jobs:
include: include:
- stage: test - # workaround for python 3.7 on travis https://github.com/travis-ci/travis-ci/issues/9815#issuecomment-401756442
python: '2.7' stage: test
env: DRF=3.7 python: '3.7'
dist: xenial
sudo: required
- -
python: '3.6' python: '3.6'
env: DRF=master env: TOXENV=djmaster
- - # readthedocs uses python 3.5 for building
python: '3.5' python: '3.5'
env: TOXENV=docs env: TOXENV=docs
- -
python: '2.7' python: '3.6'
env: TOXENV=lint env: TOXENV=lint
- stage: publish - stage: publish
@@ -40,7 +40,7 @@ jobs:
allow_failures: allow_failures:
- env: TOXENV=lint - env: TOXENV=lint
- env: DRF=master - env: TOXENV=djmaster
fast_finish: true fast_finish: true
@@ -49,20 +49,16 @@ install:
before_script: before_script:
- coverage erase - 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: script:
- 'if [[ "$USE_DETOX" == "yes" ]]; then detox; else tox; fi' - tox
after_success: after_success:
- coverage combine - |
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then coverage report; fi' if [[ -z "$TOXENV" && -z "$PYPI_DEPLOY" ]]; then
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then codecov; fi' chmod +x coverage.sh
./coverage.sh
fi
branches: branches:
only: 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 $ virtualenv venv
$ source venv/bin/activate $ source venv/bin/activate
(venv) $ pip install -e .[validation] (venv) $ pip install -U -e .[validation]
(venv) $ pip install -r requirements/dev.txt (venv) $ pip install -U -r requirements/dev.txt
#. **Make your changes and check them against the test project** #. **Make your changes and check them against the test project**
+13 -16
View File
@@ -11,9 +11,9 @@ Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framewor
Compatible with Compatible with
- **Django Rest Framework**: 3.7.7, 3.8.x - **Django Rest Framework**: 3.7.7, 3.8
- **Django**: 1.11.x, 2.0.x - **Django**: 1.11, 2.0, 2.1
- **Python**: 2.7, 3.4, 3.5, 3.6 - **Python**: 2.7, 3.4, 3.5, 3.6, 3.7
Resources: Resources:
@@ -85,14 +85,14 @@ The preferred instalation method is directly from pypi:
.. code:: console .. 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 Additionally, if you want to use the built-in validation mechanisms (see `4. Validation`_), you need to install
some extra requirements: some extra requirements:
.. code:: console .. code:: console
pip install drf-yasg[validation] pip install -U drf-yasg[validation]
.. _readme-quickstart: .. _readme-quickstart:
@@ -294,7 +294,7 @@ For additional usage examples, you can take a look at the test project in the ``
$ virtualenv venv $ virtualenv venv
$ source venv/bin/activate $ source venv/bin/activate
(venv) $ cd testproj (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 migrate
(venv) $ python manage.py shell -c "import createsuperuser" (venv) $ python manage.py shell -c "import createsuperuser"
(venv) $ python manage.py runserver (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 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 Since Django Rest Framework 3.7, there is now `built in support <http://www.django-rest-framework.org/api-guide/schemas/>`__
automatic OpenAPI 2.0 schema generation. However, this generation is based on the `coreapi <http://www.coreapi.org/>`__ 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, 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: 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 Other libraries
=============== ===============
There are currently two decent Swagger schema generators that I could There are currently two decent Swagger schema generators that I could find for django-rest-framework:
find for django-rest-framework:
* `django-rest-swagger <https://github.com/marcgibbons/django-rest-swagger>`__ * `django-rest-swagger <https://github.com/marcgibbons/django-rest-swagger>`__
* `drf-openapi <https://github.com/limdauto/drf_openapi>`__ * `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 ``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 thus presents the same problems, while also being unmaintained. ``drf-openapi`` was
schemas, but ultimately still falls short in code generation because the responses are plain of lacking support for `discontinued by the author <https://github.com/limdauto/drf_openapi/commit/1673c6e039eec7f089336a83bdc31613f32f7e21>`_
named schemas. on April 3rd, 2018.
Both projects are also currently unmantained.
************************ ************************
Third-party integrations Third-party integrations
Executable
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -ex
coverage combine
coverage report
codecov
+89 -3
View File
@@ -4,9 +4,95 @@ Changelog
********** **********
**1.9.2** **1.11.1**
********** **********
*Release date: Nov 29, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.20.1
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.41
- **FIXED:** ``minLength`` and ``maxLength`` will now also work for ``ListSerializer`` in addition to ``ListField``
- **FIXED:** ``MultipleChoiceField`` will now use the ``multi`` ``collectionFormat`` where appropriate (:issue:`257`)
- **FIXED:** the ``format``, ``pattern``, ``enum``, ``min_length`` and ``max_length`` attributes of
``coreschema.Schema`` will now be persited into the converted ``openapi.Parameter`` (:issue:`212`, :pr:`233`)
**********
**1.11.0**
**********
*Release date: Oct 14, 2018*
- **ADDED:** ``PERSIST_AUTH``, ``REFETCH_SCHEMA_WITH_AUTH``, ``REFETCH_SCHEMA_ON_LOGOUT``
settings and related javascript implementation for persisting authentication data to swagger-ui localStorage
- **IMPROVED:** UI-enabled views will now no longer generate the full specification document twice; the HTML part
of the view will only generate a barebones ``Swagger`` object with no ``paths`` and ``definitions``
- **IMPROVED:** added the ``FETCH_SCHEMA_WITH_QUERY`` setting to enable fetching of the schema document using
query parameters passed to the UI view (:issue:`208`)
- **IMPROVED:** added support for the very common ``x-nullable`` extension (:issue:`217`)
- **IMPROVED:** extensibility of some classes was improved by adding more extension points, together with more blocks
for ``swagger-ui.html``/``redoc.html`` and some JavaScript hooks in ``swagger-ui-init.js``
- **FIXED:** removed usage of ``inspect.signature`` on python 2.7 (:issue:`222`)
**********
**1.10.2**
**********
*Release date: Sep 13, 2018*
- **ADDED:** added the ``DISPLAY_OPERATION_ID`` ``swagger-ui`` setting
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.38
- **IMPROVED:** Operation summary will now be parsed from multi-line view method docstrings (:issue:`205`)
- **IMPROVED:** ``pattern`` will now work on any field with a ``RegexValidator``
(would previously not appear on fields with special formats such as ``EmailField``)
- **FIXED:** fixed an issue with ``RelatedFieldInspector`` handling of nested serializers
- **FIXED:** fixed handling of ``reverse_lazy`` in URL settings (:issue:`209`)
**********
**1.10.1**
**********
*Release date: Sep 10, 2018*
- **ADDED:** added the ``SPEC_URL`` setting for controlling the download link in ``swagger-ui`` and ``ReDoc``
- **ADDED:** updated ``ReDoc`` settings (added ``NATIVE_SCROLLBARS`` and ``REQUIRED_PROPS_FIRST``)
- **ADDED:** added ``extra_styles`` and ``extra_scripts`` blocks to ui templates (:issue:`178`)
- **IMPROVED:** updated ``swagger-ui`` to version 3.18.2
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.37
- **FIXED:** stopped generating invalid OpenAPI by improper placement of ``readOnly`` Schemas
- **FIXED:** fixed broken CSS when ``USE_SESSION_AUTH=False``
- **FIXED:** fixed implementation of ``operation_summary`` and ``deprecated`` (:pr:`194`, :pr:`198`)
- **FIXED:** fixed a bug related to nested ``typing`` hints (:pr:`195`)
- **FIXED:** removed dependency on ``future`` (:issue:`196`)
- **FIXED:** fixed exceptions logged for fields with ``default=None`` (:issue:`203`)
- **FIXED:** fixed ``request_body=no_body`` handling and related tests (:issue:`188`, :issue:`199`)
**********
**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* *Release date: Aug 03, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.17.6 - **IMPROVED:** updated ``swagger-ui`` to version 3.17.6
@@ -24,7 +110,7 @@ Changelog
- **IMPROVED:** added a ``swagger_fake_view`` marker to more easily detect mock views in view methods; - **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 ``getattr(self, 'swagger_fake_view', False)`` inside a view method like ``get_serializer_class`` will tell you if the
view instnace is being used for swagger schema introspection (:issue:`154`) view instance is being used for swagger schema introspection (:issue:`154`)
- **IMPROVED:** updated ``swagger-ui`` to version 3.17.1 - **IMPROVED:** updated ``swagger-ui`` to version 3.17.1
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.25 - **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.25
- **FIXED:** fixed wrong handling of duplicate urls in urlconf (:pr:`155`) - **FIXED:** fixed wrong handling of duplicate urls in urlconf (:pr:`155`)
@@ -39,7 +125,7 @@ Changelog
- **ADDED:** added ``DEFAULT_GENERATOR_CLASS`` setting and ``--generator-class`` argument to the ``generate_swagger`` - **ADDED:** added ``DEFAULT_GENERATOR_CLASS`` setting and ``--generator-class`` argument to the ``generate_swagger``
management command (:issue:`140`) management command (:issue:`140`)
- **FIXED:** fixed wrongly required ``'count'`` response field on ``CursorPagination`` (:issue:`141`) - **FIXED:** fixed wrongly required ``'count'`` response field on ``CursorPagination`` (:issue:`141`)
- **FIXED:** fixed some cases where ``swagger_extra_fields`` would not be handlded (:pr:`142`) - **FIXED:** fixed 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`) - **FIXED:** fixed crash when encountering ``coreapi.Fields``\ s without a ``schema`` (:issue:`143`)
********* *********
+3 -1
View File
@@ -155,7 +155,9 @@ texinfo_documents = [
'Miscellaneous'), 'Miscellaneous'),
] ]
autodoc_default_flags = ['private-members'] autodoc_default_options = {
'private-members': None
}
autodoc_member_order = 'bysource' autodoc_member_order = 'bysource'
autoclass_content = 'both' autoclass_content = 'both'
autodoc_mock_imports = [] autodoc_mock_imports = []
+54
View File
@@ -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. 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 Serializer ``Meta`` nested class
******************************** ********************************
@@ -333,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 Another caveat that stems from this is that any serializer named "``NestedSerializer``" will be forced inline
unless it has a ``ref_name`` set explicitly. unless it has a ``ref_name`` set explicitly.
.. _Python 3 type hinting: https://docs.python.org/3/library/typing.html
+11 -3
View File
@@ -2,6 +2,14 @@
Customizing the web UI Customizing the web UI
###################### ######################
There is currently no pluggable way of customizing the web UI apart from the settings available in The web UI can be customized using the settings available in :ref:`swagger-ui-settings` and :ref:`redoc-ui-settings`.
:ref:`swagger-ui-settings` and :ref:`redoc-ui-settings`. If you really need to, you can override one of the
``drf-yasg/swagger-ui.html`` or ``drf-yasg/redoc.html`` templates that are used for rendering. You can also extend one of the `drf-yasg/swagger-ui.html`_ or `drf-yasg/redoc.html`_ templates that are used for
rendering. See the template source code (linked above) for a complete list of customizable blocks.
The ``swagger-ui`` view has some quite involed JavaScript hooks used for some functionality, which you might also
want to review at `drf-yasg/swagger-ui-init.js`_.
.. _drf-yasg/swagger-ui.html: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/swagger-ui.html
.. _drf-yasg/swagger-ui-init.js: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/static/drf-yasg/swagger-ui-init.js
.. _drf-yasg/redoc.html: https://github.com/axnsan12/drf-yasg/blob/master/src/drf_yasg/templates/drf-yasg/redoc.html
+131 -13
View File
@@ -27,16 +27,27 @@ Example:
} }
REDOC_SETTINGS = { REDOC_SETTINGS = {
'LAZY_RENDERING': True, 'LAZY_RENDERING': False,
... ...
} }
.. _url-settings:
All settings which configure URLs (``LOGIN_URL``, ``SPEC_URL``, ``VALIDATOR_URL``, etc.) can accept several forms of
input:
* A view name: `urls.reverse()` will be used to reverse-resolve the name
* A 2-tuple of ``(view_name, kwargs)```: `urls.reverse()` will be used to reverse-resolve the name using the given
`kwargs`; `kwargs` must be a dict
* A 3-tuple of ``(view_name, args, kwargs)```: `urls.reverse()` will be used to reverse-resolve the name using the given
`args` and `kwargs`; `args`, `kwargs` must be a tuple/list and a dict respectively
* A URL, which will be used as-is
The possible settings and their default values are as follows: The possible settings and their default values are as follows:
******************** ****************
``SWAGGER_SETTINGS`` SWAGGER_SETTINGS
******************** ****************
.. _default-class-settings: .. _default-class-settings:
@@ -76,6 +87,7 @@ to this list.
:class:`'drf_yasg.inspectors.DictFieldInspector' <.inspectors.DictFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.DictFieldInspector' <.inspectors.DictFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.HiddenFieldInspector' <.inspectors.HiddenFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.HiddenFieldInspector' <.inspectors.HiddenFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.RecursiveFieldInspector' <.inspectors.RecursiveFieldInspector>`, |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.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \
:class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \ :class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \
``]`` ``]``
@@ -104,6 +116,14 @@ Paginator inspectors given to :func:`@swagger_auto_schema <.swagger_auto_schema>
Swagger document attributes 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-swagger-settings:
DEFAULT_INFO DEFAULT_INFO
@@ -183,6 +203,15 @@ Swagger UI settings
Swagger UI configuration settings. |br| Swagger UI configuration settings. |br|
See https://github.com/swagger-api/swagger-ui/blob/112bca906553a937ac67adc2e500bdeed96d067b/docs/usage/configuration.md#parameters. See https://github.com/swagger-api/swagger-ui/blob/112bca906553a937ac67adc2e500bdeed96d067b/docs/usage/configuration.md#parameters.
SPEC_URL
--------
URL pointing to a swagger document for use by swagger-ui. The default behaviour is to append ``?format=openapi`` to the
URL which serves the UI; see :ref:`note on URL settings <url-settings>` above.
**Default**: :python:`None` |br|
*Maps to parameter*: ``url``
VALIDATOR_URL VALIDATOR_URL
------------- -------------
@@ -193,6 +222,40 @@ set to ``None`` to remove the badge.
**Default**: :python:`'http://online.swagger.io/validator/'` |br| **Default**: :python:`'http://online.swagger.io/validator/'` |br|
*Maps to parameter*: ``validatorUrl`` *Maps to parameter*: ``validatorUrl``
PERSIST_AUTH
------------
Persist swagger-ui authorization data to local storage. |br|
**WARNING:** This may be a security risk as the credentials are stored unencrypted and can be accessed
by all javascript code running on the same domain.
**Default**: :python:`'False` |br|
*Maps to parameter*: -
REFETCH_SCHEMA_WITH_AUTH
------------------------
Re-fetch the OpenAPI document with the new credentials after authorization is performed through swagger-ui.
**Default**: :python:`'False` |br|
*Maps to parameter*: -
REFETCH_SCHEMA_ON_LOGOUT
------------------------
Re-fetch the OpenAPI document without credentials after authorization is removed through swagger-ui.
**Default**: :python:`'False` |br|
*Maps to parameter*: -
FETCH_SCHEMA_WITH_QUERY
-----------------------
Fetch the OpenAPI document using the query parameters passed to the swagger-ui page request.
**Default**: :python:`'True` |br|
*Maps to parameter*: -
OPERATIONS_SORTER OPERATIONS_SORTER
----------------- -----------------
@@ -303,9 +366,17 @@ This does not filter the operations from the display.
**Default**: :python:`['get','put','post','delete','options','head','patch','trace']` |br| **Default**: :python:`['get','put','post','delete','options','head','patch','trace']` |br|
*Maps to parameter*: ``supportedSubmitMethods`` *Maps to parameter*: ``supportedSubmitMethods``
****************** DISPLAY_OPERATION_ID
``REDOC_SETTINGS`` --------------------
******************
Controls the display of operationId in operations list.
**Default**: :python:`True`
*Maps to parameter*: ``displayOperationId``
**************
REDOC_SETTINGS
**************
.. _redoc-ui-settings: .. _redoc-ui-settings:
@@ -315,29 +386,76 @@ ReDoc UI settings
ReDoc UI configuration settings. |br| ReDoc UI configuration settings. |br|
See https://github.com/Rebilly/ReDoc#configuration. See https://github.com/Rebilly/ReDoc#configuration.
SPEC_URL
--------
URL pointing to a swagger document for use by ReDoc. The default behaviour is to append ``?format=openapi`` to the
URL which serves the UI; see :ref:`note on URL settings <url-settings>` above.
**Default**: :python:`None` |br|
*Maps to attribute*: ``spec-url``
LAZY_RENDERING LAZY_RENDERING
-------------- --------------
**Default**: :python:`True` |br| If set, enables lazy rendering mode in ReDoc. This mode is useful for APIs with big number of operations (e.g. > 50).
*Maps to attribute*: ``lazy-rendering`` In this mode ReDoc shows initial screen ASAP and then renders the rest operations asynchronously while showing
progress bar on the top.
**NOTE:** this feature might be removed in future versions of ReDoc (see https://github.com/Rebilly/ReDoc/issues/475)
**Default**: :python:`False` |br|
*Maps to attribute*: ``lazyRendering``
HIDE_HOSTNAME HIDE_HOSTNAME
------------- -------------
If set, the protocol and hostname is not shown in the operation definition.
**Default**: :python:`False` |br| **Default**: :python:`False` |br|
*Maps to attribute*: ``hide-hostname`` *Maps to attribute*: ``hideHostname``
EXPAND_RESPONSES EXPAND_RESPONSES
---------------- ----------------
Specify which responses to expand by default by response codes. Values should be passed as comma-separated list without
spaces e.g. expandResponses="200,201". Special value "all" expands all responses by default.
Be careful: this option can slow-down documentation rendering time.
**Default**: :python:`'all'` |br| **Default**: :python:`'all'` |br|
*Maps to attribute*: ``expand-responses`` *Maps to attribute*: ``expandResponses``
PATH_IN_MIDDLE PATH_IN_MIDDLE
-------------- --------------
Show path link and HTTP verb in the middle panel instead of the right one.
**Default**: :python:`False` |br| **Default**: :python:`False` |br|
*Maps to attribute*: ``path-in-middle-panel`` *Maps to attribute*: ``pathInMiddlePanel``
NATIVE_SCROLLBARS
-----------------
Use native scrollbar for sidemenu instead of perfect-scroll (scrolling performance optimization for big specs).
**Default**: :python:`False` |br|
*Maps to attribute*: ``nativeScrollbars``
REQUIRED_PROPS_FIRST
--------------------
Show required properties first ordered in the same order as in required array.
**Default**: :python:`False` |br|
*Maps to attribute*: ``requiredPropsFirst``
FETCH_SCHEMA_WITH_QUERY
-----------------------
Fetch the OpenAPI document using the query parameters passed to the ReDoc page request.
**Default**: :python:`'True` |br|
*Maps to parameter*: -
.. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name .. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name
+88 -247
View File
@@ -3,6 +3,14 @@
"requires": true, "requires": true,
"lockfileVersion": 1, "lockfileVersion": 1,
"dependencies": { "dependencies": {
"@babel/runtime": {
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.1.5.tgz",
"integrity": "sha512-xKnPpXG/pvK1B90JkwwxSGii90rQGKtzcMt2gI5G6+M0REXaq6rOHsGC2ay6/d0Uje7zzvSzjEzfR3ENhFlrfA==",
"requires": {
"regenerator-runtime": "^0.12.0"
}
},
"argparse": { "argparse": {
"version": "1.0.10", "version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
@@ -11,25 +19,6 @@
"sprintf-js": "~1.0.2" "sprintf-js": "~1.0.2"
} }
}, },
"asap": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
"integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY="
},
"base64-js": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz",
"integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw=="
},
"buffer": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.2.0.tgz",
"integrity": "sha512-nUJyfChH7PMJy75eRDCCKtszSEFokUNXC1hNVSe+o+VdcgvDPLs20k3v8UXI8ruRYAJiYtyRea8mYyqPxoHWDw==",
"requires": {
"base64-js": "^1.0.2",
"ieee754": "^1.1.4"
}
},
"call-me-maybe": { "call-me-maybe": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.1.tgz", "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.1.tgz",
@@ -41,9 +30,9 @@
"integrity": "sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q==" "integrity": "sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q=="
}, },
"clipboard": { "clipboard": {
"version": "2.0.1", "version": "2.0.4",
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.1.tgz", "resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.4.tgz",
"integrity": "sha512-7yhQBmtN+uYZmfRjjVjKa0dZdWuabzpSKGtyQZN+9C8xlC788SSJjOHWh7tzurfwTqTD5UDYAhIv5fRJg3sHjQ==", "integrity": "sha512-Vw26VSLRpJfBofiVaFb/I8PVfdI1OxKcYShe6fm0sP/DtmiWQNCjhM/okTvdCo0G+lMMm1rMYbk4IK4x1X+kgQ==",
"optional": true, "optional": true,
"requires": { "requires": {
"good-listener": "^1.2.2", "good-listener": "^1.2.2",
@@ -51,34 +40,6 @@
"tiny-emitter": "^2.0.0" "tiny-emitter": "^2.0.0"
} }
}, },
"core-js": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-1.2.7.tgz",
"integrity": "sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY="
},
"css-color-keywords": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz",
"integrity": "sha1-/qJhbcZ2spYmhrOvjb2+GAskTgU="
},
"css-to-react-native": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-2.2.1.tgz",
"integrity": "sha512-v++LRcf633phJiYZBDqtmGPj3+BVof0isd2jgwYLWZJ5YSuhCkrfYtDsNhM6oJthiEco0f9tDVJ1vUkDJNgGEA==",
"requires": {
"css-color-keywords": "^1.0.0",
"fbjs": "^0.8.5",
"postcss-value-parser": "^3.3.0"
}
},
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
"ms": "2.0.0"
}
},
"decko": { "decko": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/decko/-/decko-1.2.0.tgz", "resolved": "https://registry.npmjs.org/decko/-/decko-1.2.0.tgz",
@@ -96,17 +57,9 @@
"integrity": "sha1-ZyIm3HTI95mtNTB9+TaroRrNYBg=" "integrity": "sha1-ZyIm3HTI95mtNTB9+TaroRrNYBg="
}, },
"dompurify": { "dompurify": {
"version": "1.0.7", "version": "1.0.8",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-1.0.7.tgz", "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-1.0.8.tgz",
"integrity": "sha512-1xK0JEda/jvIm3SgqHXKvRCh3AbEKCyBbUAGpNCMVIljBD145cPvBR66JSj3O4SdscFUx5NXsDkJpz6vDT8KLg==" "integrity": "sha512-vetRFbN1SXSPfP3ClIiYnxTrXquSqakBEOoB5JESn0SVcSYzpu6ougjakpKnskGctYdlNpwf+riUHSkG7d4XUw=="
},
"encoding": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz",
"integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=",
"requires": {
"iconv-lite": "~0.4.13"
}
}, },
"esprima": { "esprima": {
"version": "4.0.1", "version": "4.0.1",
@@ -123,20 +76,6 @@
"resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
"integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc="
}, },
"fbjs": {
"version": "0.8.17",
"resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz",
"integrity": "sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=",
"requires": {
"core-js": "^1.0.0",
"isomorphic-fetch": "^2.1.1",
"loose-envify": "^1.0.0",
"object-assign": "^4.1.0",
"promise": "^7.1.1",
"setimmediate": "^1.0.5",
"ua-parser-js": "^0.7.18"
}
},
"foreach": { "foreach": {
"version": "2.0.5", "version": "2.0.5",
"resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz",
@@ -165,41 +104,12 @@
"delegate": "^3.1.2" "delegate": "^3.1.2"
} }
}, },
"has-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz",
"integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo="
},
"hoist-non-react-statics": { "hoist-non-react-statics": {
"version": "2.5.5", "version": "3.2.0",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz", "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.2.0.tgz",
"integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw==" "integrity": "sha512-3IascCRfaEkbmHjJnUxWSspIUE1okLPjGTMVXW8zraUo1t3yg1BadKAxAGILHwgoBzmMnzrgeeaDGBvpuPz6dA==",
},
"iconv-lite": {
"version": "0.4.23",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz",
"integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==",
"requires": { "requires": {
"safer-buffer": ">= 2.1.2 < 3" "react-is": "^16.3.2"
}
},
"ieee754": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz",
"integrity": "sha512-GguP+DRY+pJ3soyIiGPTvdiVXjZ+DbXOxGpXn3eMvNW4x4irjqXm4wHKscC+TfxSJ0yw/S1F24tqdMNsMZTiLA=="
},
"is-stream": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
"integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ="
},
"isomorphic-fetch": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz",
"integrity": "sha1-YRrhrPFPXoH3KVB0coGf6XM1WKk=",
"requires": {
"node-fetch": "^1.0.1",
"whatwg-fetch": ">=0.10.0"
} }
}, },
"js-tokens": { "js-tokens": {
@@ -225,14 +135,13 @@
} }
}, },
"json-schema-ref-parser": { "json-schema-ref-parser": {
"version": "5.1.2", "version": "6.0.2",
"resolved": "https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-5.1.2.tgz", "resolved": "https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-6.0.2.tgz",
"integrity": "sha512-gP0mSqqkG99xNeA4F6bf2pXQYv5fFqe9SybbKO9qSMmyzzfFFIqd16s9Y65mRWKzZ0muTjyEtcSE/hLZLvIjZw==", "integrity": "sha512-EENU7mrmuBAdjSsAEJD8mMvodZyDhLBEfuSUBSIMuXqjs+cfMbFaxS8f6+ky675jetRzGzCdhzAU3y2VEtquvQ==",
"requires": { "requires": {
"call-me-maybe": "^1.0.1", "call-me-maybe": "^1.0.1",
"debug": "^3.1.0",
"js-yaml": "^3.12.0", "js-yaml": "^3.12.0",
"ono": "^4.0.5" "ono": "^4.0.10"
} }
}, },
"loose-envify": { "loose-envify": {
@@ -244,9 +153,9 @@
} }
}, },
"lunr": { "lunr": {
"version": "2.3.1", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.1.tgz", "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.5.tgz",
"integrity": "sha1-ETYWorYC3cEJMqe/ik5uV+v+zfI=" "integrity": "sha512-EtnfmHsHJTr3u24sito9JctSxej5Ds0SgUD2Lm+qRHyLgM7BGesFlW14eNh1mil0fV5Muh8gf3dBBXzADlUlzQ=="
}, },
"mark.js": { "mark.js": {
"version": "8.11.1", "version": "8.11.1",
@@ -254,14 +163,13 @@
"integrity": "sha1-GA8fnr74sOY45BZq1S24eb6y/8U=" "integrity": "sha1-GA8fnr74sOY45BZq1S24eb6y/8U="
}, },
"marked": { "marked": {
"version": "0.3.18", "version": "git+https://github.com/markedjs/marked.git#fb48827236ed3a43e611d2adb3c070ca3f55ed8e",
"resolved": "https://registry.npmjs.org/marked/-/marked-0.3.18.tgz", "from": "git+https://github.com/markedjs/marked.git#fb48827"
"integrity": "sha512-49i2QYhfULqaXzNZpxC808PisuCTGT2fgG0zrzdCI9N3rIfAWfW0nggvbXr6zvpynZdOG5+9xNxdzP0kwZnERw=="
}, },
"memoize-one": { "memoize-one": {
"version": "4.0.0", "version": "4.0.3",
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-4.0.0.tgz", "resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-4.0.3.tgz",
"integrity": "sha512-wdpOJ4XBejprGn/xhd1i2XR8Dv1A25FJeIvR7syQhQlz9eXsv+06llcvcmBxlWVGv4C73QBsWA8kxvZozzNwiQ==" "integrity": "sha512-QmpUu4KqDmX0plH4u+tf0riMc1KHE1+lw95cMrLlXQAFOx/xnBtwhZ52XJxd9X2O6kwKBqX32kmhbhlobD0cuw=="
}, },
"min-document": { "min-document": {
"version": "2.19.0", "version": "2.19.0",
@@ -272,45 +180,31 @@
} }
}, },
"mobx-react": { "mobx-react": {
"version": "5.2.3", "version": "5.4.2",
"resolved": "https://registry.npmjs.org/mobx-react/-/mobx-react-5.2.3.tgz", "resolved": "https://registry.npmjs.org/mobx-react/-/mobx-react-5.4.2.tgz",
"integrity": "sha512-OuSlF2nJEa1PGookZcZnINbvEK4iWNNYiqUh6aebk2AkWxj3sG8OafDOQMcMYApQALTHRsrBIjOx/K8TFxcz7w==", "integrity": "sha512-alSN0KDAAOb1OkYujfoJjjk0JWxWRKO4sLGB4hN2CuvaJMrlj7bhGQe7CBMJvEFNjtJRbhJcquYVjQ3rrH2zQQ==",
"requires": { "requires": {
"hoist-non-react-statics": "^2.5.0", "hoist-non-react-statics": "^3.0.0",
"react-lifecycles-compat": "^3.0.2" "react-lifecycles-compat": "^3.0.2"
} }
}, },
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"node-fetch": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz",
"integrity": "sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==",
"requires": {
"encoding": "^0.1.11",
"is-stream": "^1.0.1"
}
},
"object-assign": { "object-assign": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
}, },
"ono": { "ono": {
"version": "4.0.5", "version": "4.0.10",
"resolved": "https://registry.npmjs.org/ono/-/ono-4.0.5.tgz", "resolved": "https://registry.npmjs.org/ono/-/ono-4.0.10.tgz",
"integrity": "sha512-ZVNuV9kJbr/2tWs83I2snrYo+WIS0DISF/xUfX9p9b6GyDD6F5N9PzHjW+p/dep6IGwSYylf1HCub5I/nM0R5Q==", "integrity": "sha512-4Xz4hlbq7MzV0I3vKfZwRvyj8tCbXODqBNzFqtkjP+KTV93zzDRju8kw1qnf6P5kcZ2+xlIq6wSCqA+euSKxhA==",
"requires": { "requires": {
"format-util": "^1.0.3" "format-util": "^1.0.3"
} }
}, },
"openapi-sampler": { "openapi-sampler": {
"version": "1.0.0-beta.13", "version": "1.0.0-beta.14",
"resolved": "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.0.0-beta.13.tgz", "resolved": "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.0.0-beta.14.tgz",
"integrity": "sha512-NReKJh92NlUmY9CDo86L1Skkx3DMDeWmiLoqMxQSX7xBpoSx8WJ1JdTb7nEwz6M7S+WDPrQsEfS5BaIW27nMrQ==", "integrity": "sha512-NNmH9YAN5AaCE4w6MQXdCrmsOJJQTswHVSp075+h+iiG+OTonpZE8HzwocozovD2imx4lamkuxGLs4E4bO4Z+g==",
"requires": { "requires": {
"json-pointer": "^0.6.0" "json-pointer": "^0.6.0"
} }
@@ -321,14 +215,12 @@
"integrity": "sha512-/2Sk/khljhdrsamjJYS5NjrH+GKEHEwh7zFSiYyxROyYKagkE4kSn2zDQDRTOMo8mpT2jikxx6yI1dG7lNP/hw==" "integrity": "sha512-/2Sk/khljhdrsamjJYS5NjrH+GKEHEwh7zFSiYyxROyYKagkE4kSn2zDQDRTOMo8mpT2jikxx6yI1dG7lNP/hw=="
}, },
"polished": { "polished": {
"version": "1.9.3", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/polished/-/polished-1.9.3.tgz", "resolved": "https://registry.npmjs.org/polished/-/polished-2.3.0.tgz",
"integrity": "sha512-4NmSD7fMFlM8roNxs7YXPv7UFRbYzb0gufR5zBxJLRzY54+zFsavxBo6zsQzP9ep6Hh3pC2pTyrpSTBEaB6IkQ==" "integrity": "sha512-G2yD9LhJy5HBuU+Im5qe70ubaJI/ZTTOIJO6GRMwJ2WSoAiPzlm8+LjAXMnm9/K0E0NumRVHvQu2HHPKQSYQjw==",
}, "requires": {
"postcss-value-parser": { "@babel/runtime": "^7.0.0"
"version": "3.3.0", }
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.0.tgz",
"integrity": "sha1-h/OPnxj3dKSrTIojL1xc6IcqnRU="
}, },
"prismjs": { "prismjs": {
"version": "1.15.0", "version": "1.15.0",
@@ -343,14 +235,6 @@
"resolved": "https://registry.npmjs.org/process/-/process-0.5.2.tgz", "resolved": "https://registry.npmjs.org/process/-/process-0.5.2.tgz",
"integrity": "sha1-FjjYqONML0QKkduVq5rrZ3/Bhc8=" "integrity": "sha1-FjjYqONML0QKkduVq5rrZ3/Bhc8="
}, },
"promise": {
"version": "7.3.1",
"resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz",
"integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==",
"requires": {
"asap": "~2.0.3"
}
},
"prop-types": { "prop-types": {
"version": "15.6.2", "version": "15.6.2",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.2.tgz", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.2.tgz",
@@ -361,17 +245,17 @@
} }
}, },
"react-dropdown": { "react-dropdown": {
"version": "1.5.0", "version": "1.6.2",
"resolved": "https://registry.npmjs.org/react-dropdown/-/react-dropdown-1.5.0.tgz", "resolved": "https://registry.npmjs.org/react-dropdown/-/react-dropdown-1.6.2.tgz",
"integrity": "sha512-rRv3a7NiP++yC1rzdjzkviC5ujq759i4SRa0M3C0Cr7loYT4Z3+JhSPekv1/04JiZNXX46cV3/g6A9kS7rkI4Q==", "integrity": "sha512-6RpKAFEVZLr53y91qnxC9rAWcoDvq8A9YstmeSV2AQgJxNFRcsreN1mJNRUctSvIwm0Hph07ouMvDc2GvfQBsA==",
"requires": { "requires": {
"classnames": "^2.2.3" "classnames": "^2.2.3"
} }
}, },
"react-hot-loader": { "react-hot-loader": {
"version": "4.3.4", "version": "4.3.12",
"resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.3.4.tgz", "resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.3.12.tgz",
"integrity": "sha512-LlKjtHq+RhDq9xm6crXojbkzrEvli5F4/RaeJ//XtDWrwwsAHDjEqKfZZiPCxv7gWV2cxE3YE8TXeE9BDzLqOA==", "integrity": "sha512-GMM4TsqUVss2QPe+Y33NlgydA5/+7tAVQxR0rZqWvBpapM8JhD7p6ymMwSZzr5yxjoXXlK/6P6qNQBOqm1dqdg==",
"requires": { "requires": {
"fast-levenshtein": "^2.0.6", "fast-levenshtein": "^2.0.6",
"global": "^4.3.0", "global": "^4.3.0",
@@ -379,12 +263,19 @@
"prop-types": "^15.6.1", "prop-types": "^15.6.1",
"react-lifecycles-compat": "^3.0.4", "react-lifecycles-compat": "^3.0.4",
"shallowequal": "^1.0.2" "shallowequal": "^1.0.2"
},
"dependencies": {
"hoist-non-react-statics": {
"version": "2.5.5",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz",
"integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw=="
}
} }
}, },
"react-is": { "react-is": {
"version": "16.4.2", "version": "16.6.3",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.4.2.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.6.3.tgz",
"integrity": "sha512-rI3cGFj/obHbBz156PvErrS5xc6f1eWyTwyV4mo0vF2lGgXgS+mm7EKD5buLJq6jNgIagQescGSVG2YzgXt8Yg==" "integrity": "sha512-u7FDWtthB4rWibG/+mFbVd5FvdI20yde86qKGx4lVUTWmPlSWQ4QxbBIrrs+HnXGbxOUlUzTAP/VDmvCwaP2yA=="
}, },
"react-lifecycles-compat": { "react-lifecycles-compat": {
"version": "3.0.4", "version": "3.0.4",
@@ -392,48 +283,47 @@
"integrity": "sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA==" "integrity": "sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA=="
}, },
"react-tabs": { "react-tabs": {
"version": "2.2.2", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/react-tabs/-/react-tabs-2.2.2.tgz", "resolved": "https://registry.npmjs.org/react-tabs/-/react-tabs-2.3.0.tgz",
"integrity": "sha512-jZGAAoq1yknr/XF60/2kH5X3UJdR1X8ItcsLZ1mJnHfoniKcCr3shT2TK5wiS2sO0LOmqwX2BtJQX3snKd50sg==", "integrity": "sha512-pYaefgVy76/36AMEP+B8YuVVzDHa3C5UFZ3REU78zolk0qMxEhKvUFofvDCXyLZwf0RZjxIfiwok1BEb18nHyA==",
"requires": { "requires": {
"classnames": "^2.2.0", "classnames": "^2.2.0",
"prop-types": "^15.5.0" "prop-types": "^15.5.0"
} }
}, },
"redoc": { "redoc": {
"version": "2.0.0-alpha.32", "version": "2.0.0-alpha.41",
"resolved": "https://registry.npmjs.org/redoc/-/redoc-2.0.0-alpha.32.tgz", "resolved": "https://registry.npmjs.org/redoc/-/redoc-2.0.0-alpha.41.tgz",
"integrity": "sha512-hqQlQ8lnXszLOJGyrRCLtCH+yPJfS22FjbqJ9X6/KM3U46UXk7rv3jZG/quV0IIRhcyehRm6h8a6Eu18KRupng==", "integrity": "sha512-g8XnoDRRNLq2GVk8cNYKtO6cK5cPK95qdCIc6PSNo2ueBVWEQBKooriSF57B6GVuaqoOBacqlGHQDPakvBQLYA==",
"requires": { "requires": {
"classnames": "^2.2.6", "classnames": "^2.2.6",
"decko": "^1.2.0", "decko": "^1.2.0",
"dompurify": "^1.0.6", "dompurify": "^1.0.7",
"eventemitter3": "^3.0.0", "eventemitter3": "^3.0.0",
"json-pointer": "^0.6.0", "json-pointer": "^0.6.0",
"json-schema-ref-parser": "^5.1.1", "json-schema-ref-parser": "^6.0.1",
"lunr": "^2.3.0", "lunr": "^2.3.2",
"mark.js": "^8.11.1", "mark.js": "^8.11.1",
"marked": "0.3.18", "marked": "git+https://github.com/markedjs/marked.git#fb48827236ed3a43e611d2adb3c070ca3f55ed8e",
"memoize-one": "^4.0.0", "memoize-one": "^4.0.0",
"mobx-react": "^5.2.3", "mobx-react": "^5.2.5",
"openapi-sampler": "1.0.0-beta.13", "openapi-sampler": "1.0.0-beta.14",
"perfect-scrollbar": "^1.4.0", "perfect-scrollbar": "^1.4.0",
"polished": "^1.9.3", "polished": "^2.0.2",
"prismjs": "^1.15.0", "prismjs": "^1.15.0",
"prop-types": "^15.6.2", "prop-types": "^15.6.2",
"react-dropdown": "^1.3.0", "react-dropdown": "^1.6.2",
"react-hot-loader": "^4.3.3", "react-hot-loader": "^4.3.5",
"react-tabs": "^2.0.0", "react-tabs": "^2.0.0",
"slugify": "^1.2.1", "slugify": "^1.3.1",
"stickyfill": "^1.1.1", "stickyfill": "^1.1.1",
"styled-components": "^3.3.3",
"tslib": "^1.9.3" "tslib": "^1.9.3"
} }
}, },
"safer-buffer": { "regenerator-runtime": {
"version": "2.1.2", "version": "0.12.1",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.12.1.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" "integrity": "sha512-odxIc1/vDlo4iZcfXqRYFj0vpXFNoGdKMAUieAlFYO6m/nl5e9KR/beGf41z4a1FI+aQgtjhuaSlDxQ0hmkrHg=="
}, },
"select": { "select": {
"version": "1.1.2", "version": "1.1.2",
@@ -441,20 +331,15 @@
"integrity": "sha1-DnNQrN7ICxEIUoeG7B1EGNEbOW0=", "integrity": "sha1-DnNQrN7ICxEIUoeG7B1EGNEbOW0=",
"optional": true "optional": true
}, },
"setimmediate": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
"integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU="
},
"shallowequal": { "shallowequal": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz", "resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz",
"integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==" "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ=="
}, },
"slugify": { "slugify": {
"version": "1.3.0", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.3.0.tgz", "resolved": "https://registry.npmjs.org/slugify/-/slugify-1.3.3.tgz",
"integrity": "sha512-vvz+9ANt7CtdTHwJpfrsHOnGkgxky+CUPnvtzDZBZYFo/H/CdZkd5lJL7z7RqtH/x9QW/ItYYfHlcGf38CBK1w==" "integrity": "sha512-aFvcXobuowA7RqU4IBVJvqmhkREDIqsj4oIJKk6JuZ5EO1PCwtAAwDCl8TdsMs4J9zCoDAVkB9FLUElDjNcRSg=="
}, },
"sprintf-js": { "sprintf-js": {
"version": "1.0.3", "version": "1.0.3",
@@ -466,44 +351,10 @@
"resolved": "https://registry.npmjs.org/stickyfill/-/stickyfill-1.1.1.tgz", "resolved": "https://registry.npmjs.org/stickyfill/-/stickyfill-1.1.1.tgz",
"integrity": "sha1-OUE/7p0CXHSn5ZzuyyN4TMDxfwI=" "integrity": "sha1-OUE/7p0CXHSn5ZzuyyN4TMDxfwI="
}, },
"styled-components": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/styled-components/-/styled-components-3.4.0.tgz",
"integrity": "sha1-0lb7RmfmwRWn7WGrePEgKDtD3QA=",
"requires": {
"buffer": "^5.0.3",
"css-to-react-native": "^2.0.3",
"fbjs": "^0.8.16",
"hoist-non-react-statics": "^2.5.0",
"prop-types": "^15.5.4",
"react-is": "^16.3.1",
"stylis": "^3.5.0",
"stylis-rule-sheet": "^0.0.10",
"supports-color": "^3.2.3"
}
},
"stylis": {
"version": "3.5.3",
"resolved": "https://registry.npmjs.org/stylis/-/stylis-3.5.3.tgz",
"integrity": "sha512-TxU0aAscJghF9I3V9q601xcK3Uw1JbXvpsBGj/HULqexKOKlOEzzlIpLFRbKkCK990ccuxfXUqmPbIIo7Fq/cQ=="
},
"stylis-rule-sheet": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/stylis-rule-sheet/-/stylis-rule-sheet-0.0.10.tgz",
"integrity": "sha512-nTbZoaqoBnmK+ptANthb10ZRZOGC+EmTLLUxeYIuHNkEKcmKgXX1XWKkUBT2Ac4es3NybooPe0SmvKdhKJZAuw=="
},
"supports-color": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-3.2.3.tgz",
"integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=",
"requires": {
"has-flag": "^1.0.0"
}
},
"swagger-ui-dist": { "swagger-ui-dist": {
"version": "3.17.6", "version": "3.20.1",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.17.6.tgz", "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.20.1.tgz",
"integrity": "sha1-37Y7uHZdOKNzjPWUZYad4W3Uczk=" "integrity": "sha512-iqFNNmJWH24leUj/ohS5iZTHLZSPZse8c9F+WSCMi6ZJcRBgYKcT413c8BR5BEdKvU1kkIwvYy7C8DOjTRq9hQ=="
}, },
"tiny-emitter": { "tiny-emitter": {
"version": "2.0.2", "version": "2.0.2",
@@ -515,16 +366,6 @@
"version": "1.9.3", "version": "1.9.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz",
"integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ=="
},
"ua-parser-js": {
"version": "0.7.18",
"resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.18.tgz",
"integrity": "sha512-LtzwHlVHwFGTptfNSgezHp7WUlwiqb0gA9AALRbKaERfxwJoiX0A73QbTToxteIAuIaFshhgIZfqK8s7clqgnA=="
},
"whatwg-fetch": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz",
"integrity": "sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng=="
} }
} }
} }
+2 -2
View File
@@ -1,8 +1,8 @@
{ {
"name": "drf-yasg", "name": "drf-yasg",
"dependencies": { "dependencies": {
"redoc": "^2.0.0-alpha.32", "redoc": "^2.0.0-alpha.41",
"swagger-ui-dist": "^3.17.6" "swagger-ui-dist": "^3.20.1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
+1
View File
@@ -1,2 +1,3 @@
-r requirements/setup.txt
.[validation] .[validation]
-r requirements/heroku.txt -r requirements/heroku.txt
-2
View File
@@ -1,9 +1,7 @@
coreapi>=2.3.3 coreapi>=2.3.3
coreschema>=0.0.4 coreschema>=0.0.4
openapi_codec>=1.3.2
ruamel.yaml>=0.15.34 ruamel.yaml>=0.15.34
inflection>=0.3.1 inflection>=0.3.1
future>=0.16.0
six>=1.10.0 six>=1.10.0
uritemplate>=3.0.0 uritemplate>=3.0.0
+1 -1
View File
@@ -1,4 +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 tox.txt
-r test.txt -r test.txt
-r lint.txt -r lint.txt
+1 -1
View File
@@ -4,5 +4,5 @@ sphinx_rtd_theme>=0.2.4
Pillow>=4.3.0 Pillow>=4.3.0
readme_renderer>=17.2 readme_renderer>=17.2
Django>=2.0,<2.1 Django>=2.0
djangorestframework_camel_case>=0.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 # needed to build the package setup_requires in setup.py
# do not unpin this (see setup.py) setuptools-scm>=3.0.6
setuptools_scm==1.15.6
+1 -1
View File
@@ -1,5 +1,5 @@
# requirements for running the tests via pytest # 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-pythonpath>=0.7.1
pytest-cov>=2.5.1 pytest-cov>=2.5.1
pytest-xdist>=1.22.0 pytest-xdist>=1.22.0
+1 -2
View File
@@ -1,5 +1,4 @@
# requirements for building and running tox # requirements for building and running tox
tox>=2.9.1,<3.0.0 tox>=3.1.2
detox>=0.11
-r setup.txt -r setup.txt
+1 -1
View File
@@ -1 +1 @@
python-3.6.4 python-3.6.6
Regular → Executable
+60 -82
View File
@@ -1,10 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import distutils.core from __future__ import print_function
import io import io
import os import os
import random
import string
import sys import sys
from setuptools import find_packages, setup from setuptools import find_packages, setup
@@ -22,88 +21,67 @@ requirements_setup = read_req('setup.txt')
requirements_validation = read_req('validation.txt') requirements_validation = read_req('validation.txt')
def _install_setup_requires(attrs): def drf_yasg_setup(**kwargs):
# copied from setuptools setup(
dist = distutils.core.Distribution(dict( name='drf-yasg',
(k, v) for k, v in attrs.items() packages=find_packages('src'),
if k in ('dependency_links', 'setup_requires') package_dir={'': 'src'},
)) include_package_data=True,
# Honor setup.cfg's options. install_requires=requirements,
dist.parse_config_files(ignore_option_errors=True) setup_requires=requirements_setup,
if dist.setup_requires: extras_require={
dist.fetch_build_eggs(dist.setup_requires) '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:
# try to install setuptools_scm before setuptools does it, otherwise our monkey patch below will come too early drf_yasg_setup(use_scm_version=True)
# (setuptools_scm adds find_files hooks into setuptools on install) except LookupError as e:
_install_setup_requires({'setup_requires': requirements_setup}) if os.getenv('CI', 'false') == 'true' or os.getenv('TRAVIS', 'false') == 'true':
except Exception: # don't silently fail on travis - we don't want to accidentally push a dummy version to PyPI
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:
raise raise
rnd = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16)) if 'setuptools-scm' in str(e):
version_kwargs = {'version': '0.0.0.dummy+' + rnd} import time
setup( timestamp_ms = int(time.time() * 1000)
name='drf-yasg', timestamp_str = hex(timestamp_ms)[2:].zfill(16)
packages=find_packages('src'), dummy_version = '0.0.0rc0+noscm' + timestamp_str
package_dir={'': 'src'},
include_package_data=True, drf_yasg_setup(version=dummy_version)
install_requires=requirements, print(str(e), file=sys.stderr)
setup_requires=requirements_setup, print("failed to detect version, build was done using dummy version " + dummy_version, file=sys.stderr)
extras_require={ else:
'validation': requirements_validation, raise
},
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
)
+15 -2
View File
@@ -14,6 +14,7 @@ SWAGGER_DEFAULTS = {
'drf_yasg.inspectors.DictFieldInspector', 'drf_yasg.inspectors.DictFieldInspector',
'drf_yasg.inspectors.HiddenFieldInspector', 'drf_yasg.inspectors.HiddenFieldInspector',
'drf_yasg.inspectors.RelatedFieldInspector', 'drf_yasg.inspectors.RelatedFieldInspector',
'drf_yasg.inspectors.SerializerMethodFieldInspector',
'drf_yasg.inspectors.SimpleFieldInspector', 'drf_yasg.inspectors.SimpleFieldInspector',
'drf_yasg.inspectors.StringDefaultFieldInspector', 'drf_yasg.inspectors.StringDefaultFieldInspector',
], ],
@@ -25,19 +26,26 @@ SWAGGER_DEFAULTS = {
'drf_yasg.inspectors.CoreAPICompatInspector', 'drf_yasg.inspectors.CoreAPICompatInspector',
], ],
'EXCLUDED_MEDIA_TYPES': ['html'],
'DEFAULT_INFO': None, 'DEFAULT_INFO': None,
'DEFAULT_API_URL': None, 'DEFAULT_API_URL': None,
'USE_SESSION_AUTH': True, 'USE_SESSION_AUTH': True,
'SECURITY_DEFINITIONS': { 'SECURITY_DEFINITIONS': {
'basic': { 'Basic': {
'type': 'basic' 'type': 'basic'
} }
}, },
'SECURITY_REQUIREMENTS': None, 'SECURITY_REQUIREMENTS': None,
'LOGIN_URL': getattr(settings, 'LOGIN_URL', None), 'LOGIN_URL': getattr(settings, 'LOGIN_URL', None),
'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None), 'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None),
'SPEC_URL': None,
'VALIDATOR_URL': '', 'VALIDATOR_URL': '',
'PERSIST_AUTH': False,
'REFETCH_SCHEMA_WITH_AUTH': False,
'REFETCH_SCHEMA_ON_LOGOUT': False,
'FETCH_SCHEMA_WITH_QUERY': True,
'OPERATIONS_SORTER': None, 'OPERATIONS_SORTER': None,
'TAGS_SORTER': None, 'TAGS_SORTER': None,
@@ -59,13 +67,18 @@ SWAGGER_DEFAULTS = {
'patch', 'patch',
'trace' 'trace'
], ],
'DISPLAY_OPERATION_ID': True,
} }
REDOC_DEFAULTS = { REDOC_DEFAULTS = {
'LAZY_RENDERING': True, 'SPEC_URL': None,
'LAZY_RENDERING': False,
'HIDE_HOSTNAME': False, 'HIDE_HOSTNAME': False,
'EXPAND_RESPONSES': 'all', 'EXPAND_RESPONSES': 'all',
'PATH_IN_MIDDLE': False, 'PATH_IN_MIDDLE': False,
'NATIVE_SCROLLBARS': False,
'REQUIRED_PROPS_FIRST': False,
'FETCH_SCHEMA_WITH_QUERY': True,
} }
IMPORT_STRINGS = [ IMPORT_STRINGS = [
+1 -2
View File
@@ -1,11 +1,10 @@
from future.utils import raise_from from six import raise_from
import copy import copy
import json import json
from collections import OrderedDict from collections import OrderedDict
from coreapi.compat import force_bytes from coreapi.compat import force_bytes
from django.utils.safestring import SafeData, SafeText
from ruamel import yaml from ruamel import yaml
from . import openapi from . import openapi
+27 -7
View File
@@ -15,7 +15,7 @@ from rest_framework.settings import api_settings as rest_framework_settings
from . import openapi from . import openapi
from .app_settings import swagger_settings from .app_settings import swagger_settings
from .errors import SwaggerGenerationError from .errors import SwaggerGenerationError
from .inspectors.field import get_basic_type_info, get_queryset_field from .inspectors.field import get_basic_type_info, get_queryset_field, get_queryset_from_view
from .openapi import ReferenceResolver from .openapi import ReferenceResolver
from .utils import force_real_str, get_consumes, get_produces from .utils import force_real_str, get_consumes, get_produces
@@ -31,8 +31,7 @@ class EndpointEnumerator(_EndpointEnumerator):
def get_path_from_regex(self, path_regex): def get_path_from_regex(self, path_regex):
if path_regex.endswith(')'): if path_regex.endswith(')'):
logger.warning("url pattern does not end in $ ('%s') - unexpected things might happen", logger.warning("url pattern does not end in $ ('%s') - unexpected things might happen", path_regex)
path_regex)
return self.unescape_path(super(EndpointEnumerator, self).get_path_from_regex(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): def should_include_endpoint(self, path, callback, app_name='', namespace='', url_name=None):
@@ -135,7 +134,7 @@ class EndpointEnumerator(_EndpointEnumerator):
"""Remove backslashe escapes from all path components outside {parameters}. This is needed because """Remove backslashe escapes from all path components outside {parameters}. This is needed because
``simplify_regex`` does not handle this correctly - note however that this implementation is ``simplify_regex`` does not handle this correctly - note however that this implementation is
**NOTE:** this might destructively affect some url regex patterns that contain metacharacters (e.g. \w, \d) **NOTE:** this might destructively affect some url regex patterns that contain metacharacters (e.g. \\w, \\d)
outside path parameter groups; if you are in this category, God help you outside path parameter groups; if you are in this category, God help you
:param str path: path possibly containing :param str path: path possibly containing
@@ -312,6 +311,27 @@ class OpenAPISchemaGenerator(object):
""" """
return self._gen.determine_path_prefix(paths) return self._gen.determine_path_prefix(paths)
def should_include_endpoint(self, path, method, view, public):
"""Check if a given endpoint should be included in the resulting schema.
:param str path: request path
:param str method: http request method
:param view: instantiated view callback
:param bool public: if True, all endpoints are included regardless of access through `request`
:returns: true if the view should be excluded
:rtype: bool
"""
return public or self._gen.has_view_permissions(path, method, view)
def get_paths_object(self, paths):
"""Construct the Swagger Paths object.
:param OrderedDict[str,openapi.PathItem] paths: mapping of paths to :class:`.PathItem` objects
:returns: the :class:`.Paths` object
:rtype: openapi.Paths
"""
return openapi.Paths(paths=paths)
def get_paths(self, endpoints, components, request, public): def get_paths(self, endpoints, components, request, public):
"""Generate the Swagger Paths for the API from the given endpoints. """Generate the Swagger Paths for the API from the given endpoints.
@@ -332,7 +352,7 @@ class OpenAPISchemaGenerator(object):
for path, (view_cls, methods) in sorted(endpoints.items()): for path, (view_cls, methods) in sorted(endpoints.items()):
operations = {} operations = {}
for method, view in methods: for method, view in methods:
if not public and not self._gen.has_view_permissions(path, method, view): if not self.should_include_endpoint(path, method, view, public):
continue continue
operation = self.get_operation(view, path, prefix, method, components, request) operation = self.get_operation(view, path, prefix, method, components, request)
@@ -347,7 +367,7 @@ class OpenAPISchemaGenerator(object):
path_suffix = '/' + path_suffix path_suffix = '/' + path_suffix
paths[path_suffix] = self.get_path_item(path, view_cls, operations) paths[path_suffix] = self.get_path_item(path, view_cls, operations)
return openapi.Paths(paths=paths), prefix return self.get_paths_object(paths), prefix
def get_operation(self, view, path, prefix, method, components, request): def get_operation(self, view, path, prefix, method, components, request):
"""Get an :class:`.Operation` for the given API endpoint (path, method). This method delegates to """Get an :class:`.Operation` for the given API endpoint (path, method). This method delegates to
@@ -425,7 +445,7 @@ class OpenAPISchemaGenerator(object):
:rtype: list[openapi.Parameter] :rtype: list[openapi.Parameter]
""" """
parameters = [] parameters = []
queryset = getattr(view_cls, 'queryset', None) queryset = get_queryset_from_view(view_cls)
for variable in sorted(uritemplate.variables(path)): for variable in sorted(uritemplate.variables(path)):
model, model_field = get_queryset_field(queryset, variable) model, model_field = get_queryset_field(queryset, variable)
+3 -3
View File
@@ -5,12 +5,12 @@ from .base import (
from .field import ( from .field import (
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector, CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector,
InlineSerializerInspector, RecursiveFieldInspector, ReferencingSerializerInspector, RelatedFieldInspector, InlineSerializerInspector, RecursiveFieldInspector, ReferencingSerializerInspector, RelatedFieldInspector,
SimpleFieldInspector, StringDefaultFieldInspector SerializerMethodFieldInspector, SimpleFieldInspector, StringDefaultFieldInspector
) )
from .query import CoreAPICompatInspector, DjangoRestResponsePagination from .query import CoreAPICompatInspector, DjangoRestResponsePagination
from .view import SwaggerAutoSchema 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.field_inspectors = swagger_settings.DEFAULT_FIELD_INSPECTORS
ViewInspector.filter_inspectors = swagger_settings.DEFAULT_FILTER_INSPECTORS ViewInspector.filter_inspectors = swagger_settings.DEFAULT_FILTER_INSPECTORS
ViewInspector.paginator_inspectors = swagger_settings.DEFAULT_PAGINATOR_INSPECTORS ViewInspector.paginator_inspectors = swagger_settings.DEFAULT_PAGINATOR_INSPECTORS
@@ -25,7 +25,7 @@ __all__ = [
# field inspectors # field inspectors
'InlineSerializerInspector', 'RecursiveFieldInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector', 'InlineSerializerInspector', 'RecursiveFieldInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector',
'SimpleFieldInspector', 'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector', 'SimpleFieldInspector', 'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector',
'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector', 'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector', 'SerializerMethodFieldInspector',
# view inspectors # view inspectors
'SwaggerAutoSchema', 'SwaggerAutoSchema',
+35 -37
View File
@@ -2,10 +2,9 @@ import inspect
import logging import logging
from rest_framework import serializers from rest_framework import serializers
from rest_framework.utils import encoders, json
from .. import openapi from .. import openapi
from ..utils import decimal_as_float, force_real_str, 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 #: Sentinel value that inspectors must return to signal that they do not know how to handle an object
NotHandled = object() NotHandled = object()
@@ -135,6 +134,19 @@ class FieldInspector(BaseInspector):
super(FieldInspector, self).__init__(view, path, method, components, request) super(FieldInspector, self).__init__(view, path, method, components, request)
self.field_inspectors = field_inspectors 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): def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
"""Convert a drf Serializer or Field instance into a Swagger object. """Convert a drf Serializer or Field instance into a Swagger object.
@@ -180,7 +192,7 @@ class FieldInspector(BaseInspector):
- arguments specified by the ``kwargs`` parameter of :meth:`._get_partial_types` - arguments specified by the ``kwargs`` parameter of :meth:`._get_partial_types`
- ``instance_kwargs`` passed to the constructor function - ``instance_kwargs`` passed to the constructor function
- ``title``, ``description``, ``required`` and ``default`` inferred from the field, - ``title``, ``description``, ``required``, ``x-nullable`` and ``default`` inferred from the field,
where appropriate where appropriate
If ``existing_object`` is not ``None``, it is updated instead of creating a new object. If ``existing_object`` is not ``None``, it is updated instead of creating a new object.
@@ -205,46 +217,32 @@ class FieldInspector(BaseInspector):
instance_kwargs['required'] = field.required instance_kwargs['required'] = field.required
if 'default' not in instance_kwargs and swagger_object_type != openapi.Items: if 'default' not in instance_kwargs and swagger_object_type != openapi.Items:
default = getattr(field, 'default', serializers.empty) default = get_field_default(field)
if default is not serializers.empty: if default not in (None, serializers.empty):
if callable(default): instance_kwargs['default'] = 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
if instance_kwargs.get('type', None) != openapi.TYPE_ARRAY: if instance_kwargs.get('type', None) != openapi.TYPE_ARRAY:
instance_kwargs.setdefault('title', title) instance_kwargs.setdefault('title', title)
instance_kwargs.setdefault('description', description) if description is not None:
instance_kwargs.setdefault('description', description)
if field.allow_null and not instance_kwargs.get('required', False) and not field.required:
instance_kwargs['x_nullable'] = True
instance_kwargs.update(kwargs) instance_kwargs.update(kwargs)
if existing_object is not None: if existing_object is not None:
assert isinstance(existing_object, swagger_object_type) assert isinstance(existing_object, swagger_object_type)
for attr, val in sorted(instance_kwargs.items()): for key, val in sorted(instance_kwargs.items()):
setattr(existing_object, attr, val) setattr(existing_object, key, val)
return existing_object 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 # 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 child_swagger_type = openapi.Schema if swagger_object_type == openapi.Schema else openapi.Items
@@ -263,7 +261,7 @@ class SerializerInspector(FieldInspector):
return NotHandled return NotHandled
def get_request_parameters(self, serializer, in_): def get_request_parameters(self, serializer, in_):
"""Convert a DRF serializer into a list of :class:`.Parameter`\ s. """Convert a DRF serializer into a list of :class:`.Parameter`\\ s.
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `serializer`. Should return :data:`.NotHandled` if this inspector does not know how to handle the given `serializer`.
@@ -377,7 +375,7 @@ class ViewInspector(BaseInspector):
) )
def serializer_to_parameters(self, serializer, in_): def serializer_to_parameters(self, serializer, in_):
"""Convert a serializer to a possibly empty list of :class:`.Parameter`\ s. """Convert a serializer to a possibly empty list of :class:`.Parameter`\\ s.
:param serializers.BaseSerializer serializer: the ``Serializer`` instance :param serializers.BaseSerializer serializer: the ``Serializer`` instance
:param str in_: the location of the parameters, one of the `openapi.IN_*` constants :param str in_: the location of the parameters, one of the `openapi.IN_*` constants
+231 -55
View File
@@ -1,5 +1,8 @@
import datetime
import inspect
import logging import logging
import operator import operator
import uuid
from collections import OrderedDict from collections import OrderedDict
from decimal import Decimal from decimal import Decimal
@@ -10,9 +13,19 @@ from rest_framework.settings import api_settings as rest_framework_settings
from .. import openapi from .. import openapi
from ..errors import SwaggerGenerationError 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 from .base import FieldInspector, NotHandled, SerializerInspector
try:
import typing
except ImportError:
typing = None
try:
from inspect import signature as inspect_signature
except ImportError:
inspect_signature = None
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -22,19 +35,6 @@ class InlineSerializerInspector(SerializerInspector):
#: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section #: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section
use_definitions = False use_definitions = False
def add_manual_fields(self, serializer, schema):
"""Set fields from the ``swagger_schem_fields`` attribute on the serializer's Meta class. This method is called
only for serializers that are converted into ``openapi.Schema`` objects.
:param serializer: serializer instance
:param openapi.Schema schema: the schema object to be modified in-place
"""
serializer_meta = getattr(serializer, 'Meta', None)
swagger_schema_fields = getattr(serializer_meta, 'swagger_schema_fields', {})
if swagger_schema_fields:
for attr, val in swagger_schema_fields.items():
setattr(schema, attr, val)
def get_schema(self, serializer): def get_schema(self, serializer):
return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions) return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions)
@@ -86,10 +86,10 @@ class InlineSerializerInspector(SerializerInspector):
ref_name = self.get_serializer_ref_name(field) ref_name = self.get_serializer_ref_name(field)
def make_schema_definition(): def make_schema_definition(serializer=field):
properties = OrderedDict() properties = OrderedDict()
required = [] required = []
for property_name, child in field.fields.items(): for property_name, child in serializer.fields.items():
property_name = self.get_property_name(property_name) property_name = self.get_property_name(property_name)
prop_kwargs = { prop_kwargs = {
'read_only': bool(child.read_only) or None 'read_only': bool(child.read_only) or None
@@ -111,20 +111,25 @@ class InlineSerializerInspector(SerializerInspector):
) )
if not ref_name and 'title' in result: if not ref_name and 'title' in result:
# on an inline model, the title is derived from the field name # 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 # it is better to just remove title from inline models
del result.title del result.title
# Provide an option to add manual paremeters to a schema
# for example, to add examples
self.add_manual_fields(field, result)
return result return result
if not ref_name or not use_references: if not ref_name or not use_references:
return make_schema_definition() return make_schema_definition()
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS) 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_schema._remove_read_only()
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 openapi.SchemaRef(definitions, ref_name)
return NotHandled return NotHandled
@@ -163,6 +168,25 @@ def get_model_field(model, field_name):
return None return None
def get_queryset_from_view(view, serializer=None):
"""Try to get the queryset of the given view
:param view: the view instance or class
:param serializer: if given, will check that the view's get_serializer_class return matches this serialzier
:return: queryset or ``None``
"""
try:
queryset = getattr(view, 'queryset', None)
if queryset is not None and serializer is not None:
# make sure the view is actually using *this* serializer
assert type(serializer) == view.get_serializer_class()
return queryset
except Exception: # pragma: no cover
return None
def get_parent_serializer(field): def get_parent_serializer(field):
"""Get the nearest parent ``Serializer`` instance for the given field. """Get the nearest parent ``Serializer`` instance for the given field.
@@ -195,7 +219,7 @@ def get_related_model(model, source):
class RelatedFieldInspector(FieldInspector): class RelatedFieldInspector(FieldInspector):
"""Provides conversions for ``RelatedField``\ s.""" """Provides conversions for ``RelatedField``\\ s."""
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs): def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs) SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
@@ -229,10 +253,18 @@ class RelatedFieldInspector(FieldInspector):
else: else:
# if the RelatedField has no queryset (e.g. read only), try to find the target model # if the RelatedField has no queryset (e.g. read only), try to find the target model
# from the view queryset or ModelSerializer model, if present # from the view queryset or ModelSerializer model, if present
view_queryset = getattr(self.view, 'queryset', None) parent_serializer = get_parent_serializer(field)
serializer_meta = getattr(get_parent_serializer(field), 'Meta', None)
this_model = getattr(view_queryset, 'model', None) or getattr(serializer_meta, 'model', None) serializer_meta = getattr(parent_serializer, 'Meta', None)
this_model = getattr(serializer_meta, 'model', None)
if not this_model:
view_queryset = get_queryset_from_view(self.view, parent_serializer)
this_model = getattr(view_queryset, 'model', None)
source = getattr(field, 'source', '') or field.field_name source = getattr(field, 'source', '') or field.field_name
if not source and isinstance(field.parent, serializers.ManyRelatedField):
source = field.parent.field_name
model = get_related_model(this_model, source) model = get_related_model(this_model, source)
model_field = get_model_field(model, target_field) model_field = get_model_field(model, target_field)
@@ -254,13 +286,22 @@ def find_regex(regex_field):
regex_validator = None regex_validator = None
for validator in regex_field.validators: for validator in regex_field.validators:
if isinstance(validator, validators.RegexValidator): if isinstance(validator, validators.RegexValidator):
if isinstance(validator, validators.URLValidator) or validator == validators.validate_ipv4_address:
# skip the default url and IP regexes because they are complex and unhelpful
# validate_ipv4_address is a RegexValidator instance in Django 1.11
continue
if regex_validator is not None: if regex_validator is not None:
# bail if multiple validators are found - no obvious way to choose # bail if multiple validators are found - no obvious way to choose
return None # pragma: no cover return None # pragma: no cover
regex_validator = validator regex_validator = validator
# regex_validator.regex should be a compiled re object... # regex_validator.regex should be a compiled re object...
pattern = getattr(getattr(regex_validator, 'regex', None), 'pattern', None) try:
pattern = getattr(getattr(regex_validator, 'regex', None), 'pattern', None)
except Exception: # pragma: no cover
logger.warning('failed to compile regex validator of ' + str(regex_field), exc_info=True)
return None
if pattern: if pattern:
# attempt some basic cleanup to remove regex constructs not supported by JavaScript # attempt some basic cleanup to remove regex constructs not supported by JavaScript
# -- swagger uses javascript-style regexes - see https://github.com/swagger-api/swagger-editor/issues/1601 # -- swagger uses javascript-style regexes - see https://github.com/swagger-api/swagger-editor/issues/1601
@@ -281,8 +322,8 @@ limit_validators = [
(validators.MaxLengthValidator, serializers.CharField, 'max_length', operator.__lt__), (validators.MaxLengthValidator, serializers.CharField, 'max_length', operator.__lt__),
# minItems and maxItems apply to lists # minItems and maxItems apply to lists
(validators.MinLengthValidator, serializers.ListField, 'min_items', operator.__gt__), (validators.MinLengthValidator, (serializers.ListField, serializers.ListSerializer), 'min_items', operator.__gt__),
(validators.MaxLengthValidator, serializers.ListField, 'max_items', operator.__lt__), (validators.MaxLengthValidator, (serializers.ListField, serializers.ListSerializer), 'max_items', operator.__lt__),
] ]
@@ -394,7 +435,7 @@ def get_basic_type_info(field):
return None return None
pattern = None pattern = None
if swagger_type == openapi.TYPE_STRING and format in (None, openapi.FORMAT_SLUG): if swagger_type == openapi.TYPE_STRING:
pattern = find_regex(field) pattern = find_regex(field)
limits = find_limits(field) limits = find_limits(field)
@@ -409,6 +450,120 @@ def get_basic_type_info(field):
return result 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 and inspect_signature:
# look for Python 3.5+ style type hinting of the return value
hint_class = inspect_signature(method).return_annotation
if not inspect.isclass(hint_class) and hasattr(hint_class, '__args__'):
hint_class = hint_class.__args__[0]
if inspect.isclass(hint_class) and 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): class SimpleFieldInspector(FieldInspector):
"""Provides conversions for fields which can be described using just ``type``, ``format``, ``pattern`` """Provides conversions for fields which can be described using just ``type``, ``format``, ``pattern``
and min/max validators. and min/max validators.
@@ -442,22 +597,28 @@ class ChoiceFieldInspector(FieldInspector):
if model_type: if model_type:
enum_type = model_type.get('type', enum_type) enum_type = model_type.get('type', enum_type)
enum_values = list(field.choices.keys())
if isinstance(field, serializers.MultipleChoiceField): if isinstance(field, serializers.MultipleChoiceField):
return SwaggerType( result = SwaggerType(
type=openapi.TYPE_ARRAY, type=openapi.TYPE_ARRAY,
items=ChildSwaggerType( items=ChildSwaggerType(
type=enum_type, type=enum_type,
enum=list(field.choices.keys()) enum=enum_values
) )
) )
if swagger_object_type == openapi.Parameter:
if result['in'] in (openapi.IN_FORM, openapi.IN_QUERY):
result.collection_format = 'multi'
else:
result = SwaggerType(type=enum_type, enum=enum_values)
return SwaggerType(type=enum_type, enum=list(field.choices.keys())) return result
return NotHandled return NotHandled
class FileFieldInspector(FieldInspector): class FileFieldInspector(FieldInspector):
"""Provides conversions for ``FileField``\ s.""" """Provides conversions for ``FileField``\\ s."""
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs): def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs) SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
@@ -523,42 +684,56 @@ try:
from djangorestframework_camel_case.render import CamelCaseJSONRenderer from djangorestframework_camel_case.render import CamelCaseJSONRenderer
from djangorestframework_camel_case.render import camelize from djangorestframework_camel_case.render import camelize
except ImportError: # pragma: no cover except ImportError: # pragma: no cover
class CamelCaseJSONFilter(FieldInspector): CamelCaseJSONParser = CamelCaseJSONRenderer = None
"""Converts property names to camelCase if ``djangorestframework_camel_case`` is used."""
pass def camelize(data):
else: return data
def camelize_string(s):
"""Hack to force ``djangorestframework_camel_case`` to camelize a plain string."""
class CamelCaseJSONFilter(FieldInspector):
"""Converts property names to camelCase if ``djangorestframework_camel_case`` is used."""
def camelize_string(self, s):
"""Hack to force ``djangorestframework_camel_case`` to camelize a plain string.
:param str s: the string
:return: camelized string
:rtype: str
"""
return next(iter(camelize({s: ''}))) return next(iter(camelize({s: ''})))
def camelize_schema(schema_or_ref, components): def camelize_schema(self, schema):
"""Recursively camelize property names for the given schema using ``djangorestframework_camel_case``.""" """Recursively camelize property names for the given schema using ``djangorestframework_camel_case``.
schema = openapi.resolve_ref(schema_or_ref, components) The target schema object must be modified in-place.
:param openapi.Schema schema: the :class:`.Schema` object
"""
if getattr(schema, 'properties', {}): if getattr(schema, 'properties', {}):
schema.properties = OrderedDict( schema.properties = OrderedDict(
(camelize_string(key), camelize_schema(val, components)) (self.camelize_string(key), self.camelize_schema(openapi.resolve_ref(val, self.components)) or val)
for key, val in schema.properties.items() for key, val in schema.properties.items()
) )
if getattr(schema, 'required', []): if getattr(schema, 'required', []):
schema.required = [camelize_string(p) for p in schema.required] schema.required = [self.camelize_string(p) for p in schema.required]
return schema_or_ref def process_result(self, result, method_name, obj, **kwargs):
if isinstance(result, openapi.Schema.OR_REF) and self.is_camel_case():
schema = openapi.resolve_ref(result, self.components)
self.camelize_schema(schema)
class CamelCaseJSONFilter(FieldInspector): return result
"""Converts property names to camelCase if ``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer`` are used."""
if CamelCaseJSONParser and CamelCaseJSONRenderer:
def is_camel_case(self): def is_camel_case(self):
return ( return (
any(issubclass(parser, CamelCaseJSONParser) for parser in self.view.parser_classes) or any(issubclass(parser, CamelCaseJSONParser) for parser in self.view.parser_classes) or
any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.view.renderer_classes) any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.view.renderer_classes)
) )
else:
def is_camel_case(self):
return False
def process_result(self, result, method_name, obj, **kwargs):
if isinstance(result, openapi.Schema.OR_REF) and self.is_camel_case():
return camelize_schema(result, self.components)
return result
try: try:
from rest_framework_recursive.fields import RecursiveField from rest_framework_recursive.fields import RecursiveField
@@ -569,14 +744,15 @@ except ImportError: # pragma: no cover
else: else:
class RecursiveFieldInspector(FieldInspector): class RecursiveFieldInspector(FieldInspector):
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)""" """Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs): def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema: if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema:
assert use_references is True, "Can not create schema for RecursiveField when use_references is False" assert use_references is True, "Can not create schema for RecursiveField when use_references is False"
ref_name = get_serializer_ref_name(field.proxied) 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, definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
ignore_unresolved=True) return openapi.SchemaRef(definitions, ref_name, ignore_unresolved=True)
return NotHandled return NotHandled
+8 -5
View File
@@ -3,14 +3,13 @@ from collections import OrderedDict
import coreschema import coreschema
from rest_framework.pagination import CursorPagination, LimitOffsetPagination, PageNumberPagination from rest_framework.pagination import CursorPagination, LimitOffsetPagination, PageNumberPagination
from drf_yasg.utils import force_real_str
from .. import openapi from .. import openapi
from ..utils import force_real_str
from .base import FilterInspector, PaginatorInspector from .base import FilterInspector, PaginatorInspector
class CoreAPICompatInspector(PaginatorInspector, FilterInspector): class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
"""Converts ``coreapi.Field``\ s to :class:`.openapi.Parameter`\ s for filters and paginators that implement a """Converts ``coreapi.Field``\\ s to :class:`.openapi.Parameter`\\ s for filters and paginators that implement a
``get_schema_fields`` method. ``get_schema_fields`` method.
""" """
@@ -45,12 +44,16 @@ class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
coreschema.String: openapi.TYPE_STRING, coreschema.String: openapi.TYPE_STRING,
coreschema.Boolean: openapi.TYPE_BOOLEAN, coreschema.Boolean: openapi.TYPE_BOOLEAN,
} }
coreschema_attrs = ['format', 'pattern', 'enum', 'min_length', 'max_length']
schema = field.schema
return openapi.Parameter( return openapi.Parameter(
name=field.name, name=field.name,
in_=location_to_in[field.location], in_=location_to_in[field.location],
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
required=field.required, required=field.required,
description=force_real_str(field.schema.description) if field.schema else None, description=force_real_str(schema.description) if schema else None,
type=coreapi_types.get(type(schema), openapi.TYPE_STRING),
**OrderedDict((attr, getattr(schema, attr, None)) for attr in coreschema_attrs)
) )
+58 -19
View File
@@ -8,8 +8,8 @@ from rest_framework.status import is_success
from .. import openapi from .. import openapi
from ..errors import SwaggerGenerationError from ..errors import SwaggerGenerationError
from ..utils import ( from ..utils import (
force_real_str, 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,
param_list_to_odict merge_params, no_body, param_list_to_odict
) )
from .base import ViewInspector from .base import ViewInspector
@@ -34,8 +34,10 @@ class SwaggerAutoSchema(ViewInspector):
operation_id = self.get_operation_id(operation_keys) operation_id = self.get_operation_id(operation_keys)
description = self.get_description() description = self.get_description()
summary = self.get_summary()
security = self.get_security() security = self.get_security()
assert security is None or isinstance(security, list), "security must be a list of securiy requirement objects" assert security is None or isinstance(security, list), "security must be a list of security requirement objects"
deprecated = self.is_deprecated()
tags = self.get_tags(operation_keys) tags = self.get_tags(operation_keys)
responses = self.get_responses() responses = self.get_responses()
@@ -43,12 +45,14 @@ class SwaggerAutoSchema(ViewInspector):
return openapi.Operation( return openapi.Operation(
operation_id=operation_id, operation_id=operation_id,
description=force_real_str(description), description=force_real_str(description),
summary=force_real_str(summary),
responses=responses, responses=responses,
parameters=parameters, parameters=parameters,
consumes=consumes, consumes=consumes,
produces=produces, produces=produces,
tags=tags, tags=tags,
security=security security=security,
deprecated=deprecated
) )
def get_request_body_parameters(self, consumes): def get_request_body_parameters(self, consumes):
@@ -59,7 +63,7 @@ class SwaggerAutoSchema(ViewInspector):
- a list of primitive Parameters parsed as form data - a list of primitive Parameters parsed as form data
:param list[str] consumes: a list of accepted MIME types as returned by :meth:`.get_consumes` :param list[str] consumes: a list of accepted MIME types as returned by :meth:`.get_consumes`
:return: a (potentially empty) list of :class:`.Parameter`\ s either ``in: body`` or ``in: formData`` :return: a (potentially empty) list of :class:`.Parameter`\\ s either ``in: body`` or ``in: formData``
:rtype: list[openapi.Parameter] :rtype: list[openapi.Parameter]
""" """
serializer = self.get_request_serializer() serializer = self.get_request_serializer()
@@ -102,7 +106,7 @@ class SwaggerAutoSchema(ViewInspector):
if body_override is not None: if body_override is not None:
if body_override is no_body: if body_override is no_body:
return None return no_body
if self.method not in self.body_methods: if self.method not in self.body_methods:
raise SwaggerGenerationError("request_body can only be applied to (" + ','.join(self.body_methods) + raise SwaggerGenerationError("request_body can only be applied to (" + ','.join(self.body_methods) +
"); are you looking for query_serializer or manual_parameters?") "); are you looking for query_serializer or manual_parameters?")
@@ -122,10 +126,13 @@ class SwaggerAutoSchema(ViewInspector):
if body_override is None and self.method in self.implicit_body_methods: if body_override is None and self.method in self.implicit_body_methods:
return self.get_view_serializer() return self.get_view_serializer()
if body_override is no_body:
return None
return body_override return body_override
def get_request_form_parameters(self, serializer): def get_request_form_parameters(self, serializer):
"""Given a Serializer, return a list of ``in: formData`` :class:`.Parameter`\ s. """Given a Serializer, return a list of ``in: formData`` :class:`.Parameter`\\ s.
:param serializer: the view's request serializer as returned by :meth:`.get_request_serializer` :param serializer: the view's request serializer as returned by :meth:`.get_request_serializer`
:rtype: list[openapi.Parameter] :rtype: list[openapi.Parameter]
@@ -155,21 +162,19 @@ class SwaggerAutoSchema(ViewInspector):
:return: modified parameters :return: modified parameters
:rtype: list[openapi.Parameter] :rtype: list[openapi.Parameter]
""" """
parameters = param_list_to_odict(parameters)
manual_parameters = self.overrides.get('manual_parameters', None) or [] manual_parameters = self.overrides.get('manual_parameters', None) or []
if any(param.in_ == openapi.IN_BODY for param in manual_parameters): # pragma: no cover if any(param.in_ == openapi.IN_BODY for param in manual_parameters): # pragma: no cover
raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body") raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body")
if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover
if any(param.in_ == openapi.IN_BODY for param in parameters.values()): if any(param.in_ == openapi.IN_BODY for param in parameters):
raise SwaggerGenerationError("cannot add form parameters when the request has a request body; " raise SwaggerGenerationError("cannot add form parameters when the request has a request body; "
"did you forget to set an appropriate parser class on the view?") "did you forget to set an appropriate parser class on the view?")
if self.method not in self.body_methods: if self.method not in self.body_methods:
raise SwaggerGenerationError("form parameters can only be applied to (" + ','.join(self.body_methods) + raise SwaggerGenerationError("form parameters can only be applied to (" + ','.join(self.body_methods) +
") HTTP methods") ") HTTP methods")
parameters.update(param_list_to_odict(manual_parameters)) return merge_params(parameters, manual_parameters)
return list(parameters.values())
def get_responses(self): def get_responses(self):
"""Get the possible responses for this view as a swagger :class:`.Responses` object. """Get the possible responses for this view as a swagger :class:`.Responses` object.
@@ -188,7 +193,11 @@ class SwaggerAutoSchema(ViewInspector):
:return: response serializer, :class:`.Schema`, :class:`.SchemaRef`, ``None`` :return: response serializer, :class:`.Schema`, :class:`.SchemaRef`, ``None``
""" """
return self._get_request_body_override() or self.get_view_serializer() body_override = self._get_request_body_override()
if body_override and body_override is not no_body:
return body_override
return self.get_view_serializer()
def get_default_responses(self): def get_default_responses(self):
"""Get the default responses determined for this view from the request serializer and request method. """Get the default responses determined for this view from the request serializer and request method.
@@ -203,8 +212,6 @@ class SwaggerAutoSchema(ViewInspector):
default_schema = self.get_default_response_serializer() default_schema = self.get_default_response_serializer()
default_schema = default_schema or '' default_schema = default_schema or ''
if any(is_form_media_type(encoding) for encoding in self.get_consumes()):
default_schema = ''
if default_schema and not isinstance(default_schema, openapi.Schema): if default_schema and not isinstance(default_schema, openapi.Schema):
default_schema = self.serializer_to_schema(default_schema) or '' default_schema = self.serializer_to_schema(default_schema) or ''
@@ -219,7 +226,7 @@ class SwaggerAutoSchema(ViewInspector):
def get_response_serializers(self): def get_response_serializers(self):
"""Return the response codes that this view is expected to return, and the serializer for each response body. """Return the response codes that this view is expected to return, and the serializer for each response body.
The return value should be a dict where the keys are possible status codes, and values are either strings, The return value should be a dict where the keys are possible status codes, and values are either strings,
``Serializer``\ s, :class:`.Schema`, :class:`.SchemaRef` or :class:`.Response` objects. See ``Serializer``\\ s, :class:`.Schema`, :class:`.SchemaRef` or :class:`.Response` objects. See
:func:`@swagger_auto_schema <.swagger_auto_schema>` for more details. :func:`@swagger_auto_schema <.swagger_auto_schema>` for more details.
:return: the response serializers :return: the response serializers
@@ -314,16 +321,40 @@ class SwaggerAutoSchema(ViewInspector):
operation_id = '_'.join(operation_keys) operation_id = '_'.join(operation_keys)
return operation_id return operation_id
def _extract_description_and_summary(self):
description = self.overrides.get('operation_description', None)
summary = self.overrides.get('operation_summary', None)
if description is None:
description = self._sch.get_description(self.path, self.method) or ''
description = description.strip().replace('\r', '')
if description and (summary is None):
# description from docstring ... do summary magic
# https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings
summary_max_len = 120 # OpenAPI 2.0 spec says summary should be under 120 characters
sections = description.split('\n\n', 1)
if len(sections) == 2:
sections[0] = sections[0].strip()
if len(sections[0]) < summary_max_len:
summary, description = sections
return description, summary
def get_description(self): def get_description(self):
"""Return an operation description determined as appropriate from the view's method and class docstrings. """Return an operation description determined as appropriate from the view's method and class docstrings.
:return: the operation description :return: the operation description
:rtype: str :rtype: str
""" """
description = self.overrides.get('operation_description', None) return self._extract_description_and_summary()[0]
if description is None:
description = self._sch.get_description(self.path, self.method) def get_summary(self):
return description """Return a summary description for this operation.
:return: the summary
:rtype: str
"""
return self._extract_description_and_summary()[1]
def get_security(self): def get_security(self):
"""Return a list of security requirements for this operation. """Return a list of security requirements for this operation.
@@ -335,6 +366,14 @@ class SwaggerAutoSchema(ViewInspector):
:rtype: list[dict[str,list[str]]]""" :rtype: list[dict[str,list[str]]]"""
return self.overrides.get('security', None) 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): 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 """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. each tag will show as a group containing the operations that use it.
+36 -8
View File
@@ -1,3 +1,4 @@
import logging
import re import re
from collections import OrderedDict from collections import OrderedDict
@@ -7,6 +8,8 @@ from inflection import camelize
from .utils import filter_none from .utils import filter_none
logger = logging.getLogger(__name__)
TYPE_OBJECT = "object" #: TYPE_OBJECT = "object" #:
TYPE_STRING = "string" #: TYPE_STRING = "string" #:
TYPE_NUMBER = "number" #: TYPE_NUMBER = "number" #:
@@ -288,6 +291,8 @@ class Paths(SwaggerDict):
class PathItem(SwaggerDict): class PathItem(SwaggerDict):
OPERATION_NAMES = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch']
def __init__(self, get=None, put=None, post=None, delete=None, options=None, def __init__(self, get=None, put=None, post=None, delete=None, options=None,
head=None, patch=None, parameters=None, **extra): head=None, patch=None, parameters=None, **extra):
"""Information about a single path """Information about a single path
@@ -312,6 +317,15 @@ class PathItem(SwaggerDict):
self.parameters = filter_none(parameters) self.parameters = filter_none(parameters)
self._insert_extras__() self._insert_extras__()
@property
def operations(self):
"""A list of all standard Operations on this PathItem object. See :attr:`.OPERATION_NAMES`.
:return: list of (method name, Operation) tuples
:rtype: list[tuple[str,Operation]]
"""
return [(k, v) for k, v in self.items() if k in PathItem.OPERATION_NAMES and v]
class Operation(SwaggerDict): class Operation(SwaggerDict):
def __init__(self, operation_id, responses, parameters=None, consumes=None, produces=None, summary=None, def __init__(self, operation_id, responses, parameters=None, consumes=None, produces=None, summary=None,
@@ -384,8 +398,6 @@ class Parameter(SwaggerDict):
:param default: default value if the parameter is not provided; must conform to parameter type :param default: default value if the parameter is not provided; must conform to parameter type
""" """
super(Parameter, self).__init__(**extra) super(Parameter, self).__init__(**extra)
if (not schema and not type) or (schema and type):
raise AssertionError("either schema or type are required for Parameter object!")
self.name = name self.name = name
self.in_ = in_ self.in_ = in_
self.description = description self.description = description
@@ -398,6 +410,10 @@ class Parameter(SwaggerDict):
self.items = items self.items = items
self.default = default self.default = default
self._insert_extras__() self._insert_extras__()
if (not schema and not type) or (schema and type):
raise AssertionError("either schema or type are required for Parameter object (not both)!")
if schema and isinstance(schema, Schema):
schema._remove_read_only()
if self['in'] == IN_PATH: if self['in'] == IN_PATH:
# path parameters must always be required # path parameters must always be required
assert required is not False, "path parameter cannot be optional" assert required is not False, "path parameter cannot be optional"
@@ -429,9 +445,9 @@ class Schema(SwaggerDict):
:param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties` :param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties`
:param list[str] required: list of requried property names :param list[str] required: list of requried property names
:param .Schema,.SchemaRef items: type of array items, only valid if `type` is ``array`` :param .Schema,.SchemaRef items: type of array items, only valid if `type` is ``array``
:param default: only valid when insider another ``Schema``\ 's ``properties``; :param default: only valid when insider another ``Schema``\\ 's ``properties``;
the default value of this property if it is not provided, must conform to the type of this Schema the default value of this property if it is not provided, must conform to the type of this Schema
:param read_only: only valid when insider another ``Schema``\ 's ``properties``; :param read_only: only valid when insider another ``Schema``\\ 's ``properties``;
declares the property as read only - it must only be sent as part of responses, never in requests declares the property as read only - it must only be sent as part of responses, never in requests
""" """
super(Schema, self).__init__(**extra) super(Schema, self).__init__(**extra)
@@ -462,6 +478,11 @@ class Schema(SwaggerDict):
if pattern and type != TYPE_STRING: if pattern and type != TYPE_STRING:
raise AssertionError("pattern can only be used when type is string") raise AssertionError("pattern can only be used when type is string")
def _remove_read_only(self):
# readOnly is only valid for Schemas inside another Schema's properties;
# when placing Schema elsewhere we must take care to remove the readOnly flag
self.pop('readOnly', '')
class _Ref(SwaggerDict): class _Ref(SwaggerDict):
ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$") ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$")
@@ -494,12 +515,12 @@ class _Ref(SwaggerDict):
ref_match = self.ref_name_re.match(self.ref) ref_match = self.ref_name_re.match(self.ref)
return resolver.get(ref_match.group('name'), scope=ref_match.group('scope')) return resolver.get(ref_match.group('name'), scope=ref_match.group('scope'))
def __setitem__(self, key, value, **kwargs): def __setitem__(self, key, value):
if key == "$ref": if key == "$ref":
return super(_Ref, self).__setitem__(key, value, **kwargs) return super(_Ref, self).__setitem__(key, value)
raise NotImplementedError("only $ref can be set on Reference objects (not %s)" % key) raise NotImplementedError("only $ref can be set on Reference objects (not %s)" % key)
def __delitem__(self, key, **kwargs): def __delitem__(self, key):
raise NotImplementedError("cannot delete property of Reference object") raise NotImplementedError("cannot delete property of Reference object")
@@ -557,6 +578,8 @@ class Response(SwaggerDict):
self.schema = schema self.schema = schema
self.examples = examples self.examples = examples
self._insert_extras__() self._insert_extras__()
if schema and isinstance(schema, Schema):
schema._remove_read_only()
class ReferenceResolver(object): class ReferenceResolver(object):
@@ -628,8 +651,13 @@ class ReferenceResolver(object):
ret = self.getdefault(name, None, scope) ret = self.getdefault(name, None, scope)
if ret is None: if ret is None:
ret = maker() ret = maker()
value = self.getdefault(name, None, scope)
assert ret is not None, "maker returned None; referenced objects cannot be None/null" 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 return ret
+83 -48
View File
@@ -1,11 +1,14 @@
import six
from django.shortcuts import render, resolve_url from django.shortcuts import render, resolve_url
from django.utils.functional import Promise
from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer
from rest_framework.utils import json from rest_framework.utils import json
from drf_yasg.openapi import Swagger
from .app_settings import redoc_settings, swagger_settings from .app_settings import redoc_settings, swagger_settings
from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
from .openapi import Swagger
from .utils import filter_none
class _SpecRenderer(BaseRenderer): class _SpecRenderer(BaseRenderer):
@@ -25,7 +28,7 @@ class _SpecRenderer(BaseRenderer):
if not isinstance(data, Swagger): # pragma: no cover if not isinstance(data, Swagger): # pragma: no cover
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response`` # if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it # in that case, it's probably better to let the default ``JSONRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58 # see https://github.com/axnsan12/drf-yasg/issues/58
return JSONRenderer().render(data, media_type, renderer_context) return JSONRenderer().render(data, media_type, renderer_context)
return codec.encode(data) return codec.encode(data)
@@ -65,32 +68,60 @@ class _UIRenderer(BaseRenderer):
# see https://github.com/axnsan12/drf-yasg/issues/58 # see https://github.com/axnsan12/drf-yasg/issues/58
return TemplateHTMLRenderer().render(swagger, accepted_media_type, renderer_context) return TemplateHTMLRenderer().render(swagger, accepted_media_type, renderer_context)
self.set_context(renderer_context, swagger) self.set_context(renderer_context, swagger)
return render( return render(renderer_context['request'], self.template, renderer_context)
renderer_context['request'],
self.template,
renderer_context
)
def set_context(self, renderer_context, swagger): def set_context(self, renderer_context, swagger=None):
renderer_context['title'] = swagger.info.title renderer_context['title'] = swagger.info.title or '' if swagger else ''
renderer_context['version'] = swagger.info.version renderer_context['version'] = swagger.info.version or '' if swagger else ''
renderer_context['swagger_settings'] = json.dumps(self.get_swagger_ui_settings())
renderer_context['redoc_settings'] = json.dumps(self.get_redoc_settings())
renderer_context['oauth2_config'] = json.dumps(self.get_oauth2_config()) renderer_context['oauth2_config'] = json.dumps(self.get_oauth2_config())
renderer_context['USE_SESSION_AUTH'] = swagger_settings.USE_SESSION_AUTH renderer_context['USE_SESSION_AUTH'] = swagger_settings.USE_SESSION_AUTH
renderer_context.update(self.get_auth_urls()) renderer_context.update(self.get_auth_urls())
def get_auth_urls(self): def resolve_url(self, to):
urls = {} if isinstance(to, Promise):
if swagger_settings.LOGIN_URL is not None: to = str(to)
urls['LOGIN_URL'] = resolve_url(swagger_settings.LOGIN_URL)
if swagger_settings.LOGOUT_URL is not None:
urls['LOGOUT_URL'] = resolve_url(swagger_settings.LOGOUT_URL)
return urls if to is None:
return None
args, kwargs = None, None
if not isinstance(to, six.string_types):
if len(to) > 2:
to, args, kwargs = to
elif len(to) == 2:
to, kwargs = to
args = args or ()
kwargs = kwargs or {}
return resolve_url(to, *args, **kwargs)
def get_auth_urls(self):
urls = {
'LOGIN_URL': self.resolve_url(swagger_settings.LOGIN_URL),
'LOGOUT_URL': self.resolve_url(swagger_settings.LOGOUT_URL),
}
return filter_none(urls)
def get_oauth2_config(self):
data = swagger_settings.OAUTH2_CONFIG
assert isinstance(data, dict), "OAUTH2_CONFIG must be a dict"
return data
class SwaggerUIRenderer(_UIRenderer):
"""Renders a swagger-ui web interface for schema browisng."""
template = 'drf-yasg/swagger-ui.html'
format = 'swagger'
def set_context(self, renderer_context, swagger=None):
super(SwaggerUIRenderer, self).set_context(renderer_context, swagger)
renderer_context['swagger_settings'] = json.dumps(self.get_swagger_ui_settings())
def get_swagger_ui_settings(self): def get_swagger_ui_settings(self):
data = { data = {
'url': self.resolve_url(swagger_settings.SPEC_URL),
'operationsSorter': swagger_settings.OPERATIONS_SORTER, 'operationsSorter': swagger_settings.OPERATIONS_SORTER,
'tagsSorter': swagger_settings.TAGS_SORTER, 'tagsSorter': swagger_settings.TAGS_SORTER,
'docExpansion': swagger_settings.DOC_EXPANSION, 'docExpansion': swagger_settings.DOC_EXPANSION,
@@ -102,40 +133,44 @@ class _UIRenderer(BaseRenderer):
'showCommonExtensions': swagger_settings.SHOW_COMMON_EXTENSIONS, 'showCommonExtensions': swagger_settings.SHOW_COMMON_EXTENSIONS,
'oauth2RedirectUrl': swagger_settings.OAUTH2_REDIRECT_URL, 'oauth2RedirectUrl': swagger_settings.OAUTH2_REDIRECT_URL,
'supportedSubmitMethods': swagger_settings.SUPPORTED_SUBMIT_METHODS, 'supportedSubmitMethods': swagger_settings.SUPPORTED_SUBMIT_METHODS,
'displayOperationId': swagger_settings.DISPLAY_OPERATION_ID,
'persistAuth': swagger_settings.PERSIST_AUTH,
'refetchWithAuth': swagger_settings.REFETCH_SCHEMA_WITH_AUTH,
'refetchOnLogout': swagger_settings.REFETCH_SCHEMA_ON_LOGOUT,
'fetchSchemaWithQuery': swagger_settings.FETCH_SCHEMA_WITH_QUERY,
} }
data = {k: v for k, v in data.items() if v is not None}
data = filter_none(data)
if swagger_settings.VALIDATOR_URL != '': if swagger_settings.VALIDATOR_URL != '':
data['validatorUrl'] = swagger_settings.VALIDATOR_URL data['validatorUrl'] = self.resolve_url(swagger_settings.VALIDATOR_URL)
return data return data
def get_redoc_settings(self):
data = {
'lazyRendering': redoc_settings.LAZY_RENDERING,
'hideHostname': redoc_settings.HIDE_HOSTNAME,
'expandResponses': redoc_settings.EXPAND_RESPONSES,
'pathInMiddle': redoc_settings.PATH_IN_MIDDLE,
}
return data
def get_oauth2_config(self):
data = swagger_settings.OAUTH2_CONFIG
assert isinstance(data, dict), "OAUTH2_CONFIG must be a dict"
return data
class SwaggerUIRenderer(_UIRenderer):
"""Renders a swagger-ui web interface for schema browisng.
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
"""
template = 'drf-yasg/swagger-ui.html'
format = 'swagger'
class ReDocRenderer(_UIRenderer): class ReDocRenderer(_UIRenderer):
"""Renders a ReDoc web interface for schema browisng. """Renders a ReDoc web interface for schema browisng."""
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
"""
template = 'drf-yasg/redoc.html' template = 'drf-yasg/redoc.html'
format = 'redoc' format = 'redoc'
def set_context(self, renderer_context, swagger=None):
super(ReDocRenderer, self).set_context(renderer_context, swagger)
renderer_context['redoc_settings'] = json.dumps(self.get_redoc_settings())
def get_redoc_settings(self):
data = {
'url': self.resolve_url(redoc_settings.SPEC_URL),
'lazyRendering': redoc_settings.LAZY_RENDERING,
'hideHostname': redoc_settings.HIDE_HOSTNAME,
'expandResponses': redoc_settings.EXPAND_RESPONSES,
'pathInMiddlePanel': redoc_settings.PATH_IN_MIDDLE,
'nativeScrollbars': redoc_settings.NATIVE_SCROLLBARS,
'requiredPropsFirst': redoc_settings.REQUIRED_PROPS_FIRST,
'fetchSchemaWithQuery': redoc_settings.FETCH_SCHEMA_WITH_QUERY,
}
return filter_none(data)
class ReDocOldRenderer(ReDocRenderer):
"""Renders a ReDoc 1.x.x web interface for schema browisng."""
template = 'drf-yasg/redoc-old.html'
+34
View File
@@ -0,0 +1,34 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Immutable=e()}(this,function(){"use strict";function t(t,e){e&&(t.prototype=Object.create(e.prototype)),t.prototype.constructor=t}function e(t){return o(t)?t:O(t)}function r(t){return u(t)?t:x(t)}function n(t){return s(t)?t:k(t)}function i(t){return o(t)&&!a(t)?t:A(t)}function o(t){return!(!t||!t[ar])}function u(t){return!(!t||!t[hr])}function s(t){return!(!t||!t[fr])}function a(t){return u(t)||s(t)}function h(t){return!(!t||!t[cr])}function f(t){return t.value=!1,t}function c(t){t&&(t.value=!0)}function _(){}function p(t,e){e=e||0;for(var r=Math.max(0,t.length-e),n=Array(r),i=0;r>i;i++)n[i]=t[i+e];return n}function v(t){return void 0===t.size&&(t.size=t.__iterate(y)),t.size}function l(t,e){if("number"!=typeof e){var r=e>>>0;if(""+r!==e||4294967295===r)return NaN;e=r}return 0>e?v(t)+e:e}function y(){return!0}function d(t,e,r){return(0===t||void 0!==r&&-r>=t)&&(void 0===e||void 0!==r&&e>=r)}function m(t,e){return w(t,e,0)}function g(t,e){return w(t,e,e)}function w(t,e,r){return void 0===t?r:0>t?Math.max(0,e+t):void 0===e?t:Math.min(e,t)}function S(t){this.next=t}function z(t,e,r,n){var i=0===t?e:1===t?r:[e,r];return n?n.value=i:n={value:i,done:!1},n}function I(){return{value:void 0,done:!0}}function b(t){return!!M(t)}function q(t){return t&&"function"==typeof t.next}function D(t){var e=M(t);return e&&e.call(t)}function M(t){var e=t&&(zr&&t[zr]||t[Ir]);return"function"==typeof e?e:void 0}function E(t){return t&&"number"==typeof t.length}function O(t){return null===t||void 0===t?T():o(t)?t.toSeq():C(t)}function x(t){return null===t||void 0===t?T().toKeyedSeq():o(t)?u(t)?t.toSeq():t.fromEntrySeq():B(t)}function k(t){return null===t||void 0===t?T():o(t)?u(t)?t.entrySeq():t.toIndexedSeq():W(t)}function A(t){return(null===t||void 0===t?T():o(t)?u(t)?t.entrySeq():t:W(t)).toSetSeq()}function j(t){this._array=t,this.size=t.length}function R(t){var e=Object.keys(t);this._object=t,this._keys=e,
this.size=e.length}function U(t){this._iterable=t,this.size=t.length||t.size}function K(t){this._iterator=t,this._iteratorCache=[]}function L(t){return!(!t||!t[qr])}function T(){return Dr||(Dr=new j([]))}function B(t){var e=Array.isArray(t)?new j(t).fromEntrySeq():q(t)?new K(t).fromEntrySeq():b(t)?new U(t).fromEntrySeq():"object"==typeof t?new R(t):void 0;if(!e)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+t);return e}function W(t){var e=J(t);if(!e)throw new TypeError("Expected Array or iterable object of values: "+t);return e}function C(t){var e=J(t)||"object"==typeof t&&new R(t);if(!e)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+t);return e}function J(t){return E(t)?new j(t):q(t)?new K(t):b(t)?new U(t):void 0}function N(t,e,r,n){var i=t._cache;if(i){for(var o=i.length-1,u=0;o>=u;u++){var s=i[r?o-u:u];if(e(s[1],n?s[0]:u,t)===!1)return u+1}return u}return t.__iterateUncached(e,r)}function P(t,e,r,n){var i=t._cache;if(i){var o=i.length-1,u=0;return new S(function(){var t=i[r?o-u:u];return u++>o?I():z(e,n?t[0]:u-1,t[1])})}return t.__iteratorUncached(e,r)}function H(t,e){return e?V(e,t,"",{"":t}):Y(t)}function V(t,e,r,n){return Array.isArray(e)?t.call(n,r,k(e).map(function(r,n){return V(t,r,n,e)})):Q(e)?t.call(n,r,x(e).map(function(r,n){return V(t,r,n,e)})):e}function Y(t){return Array.isArray(t)?k(t).map(Y).toList():Q(t)?x(t).map(Y).toMap():t}function Q(t){return t&&(t.constructor===Object||void 0===t.constructor)}function X(t,e){if(t===e||t!==t&&e!==e)return!0;if(!t||!e)return!1;if("function"==typeof t.valueOf&&"function"==typeof e.valueOf){if(t=t.valueOf(),e=e.valueOf(),t===e||t!==t&&e!==e)return!0;if(!t||!e)return!1}return"function"==typeof t.equals&&"function"==typeof e.equals&&t.equals(e)?!0:!1}function F(t,e){if(t===e)return!0;if(!o(e)||void 0!==t.size&&void 0!==e.size&&t.size!==e.size||void 0!==t.__hash&&void 0!==e.__hash&&t.__hash!==e.__hash||u(t)!==u(e)||s(t)!==s(e)||h(t)!==h(e))return!1;if(0===t.size&&0===e.size)return!0;
var r=!a(t);if(h(t)){var n=t.entries();return e.every(function(t,e){var i=n.next().value;return i&&X(i[1],t)&&(r||X(i[0],e))})&&n.next().done}var i=!1;if(void 0===t.size)if(void 0===e.size)"function"==typeof t.cacheResult&&t.cacheResult();else{i=!0;var f=t;t=e,e=f}var c=!0,_=e.__iterate(function(e,n){return(r?t.has(e):i?X(e,t.get(n,yr)):X(t.get(n,yr),e))?void 0:(c=!1,!1)});return c&&t.size===_}function G(t,e){if(!(this instanceof G))return new G(t,e);if(this._value=t,this.size=void 0===e?1/0:Math.max(0,e),0===this.size){if(Mr)return Mr;Mr=this}}function Z(t,e){if(!t)throw Error(e)}function $(t,e,r){if(!(this instanceof $))return new $(t,e,r);if(Z(0!==r,"Cannot step a Range by 0"),t=t||0,void 0===e&&(e=1/0),r=void 0===r?1:Math.abs(r),t>e&&(r=-r),this._start=t,this._end=e,this._step=r,this.size=Math.max(0,Math.ceil((e-t)/r-1)+1),0===this.size){if(Er)return Er;Er=this}}function tt(){throw TypeError("Abstract")}function et(){}function rt(){}function nt(){}function it(t){return t>>>1&1073741824|3221225471&t}function ot(t){if(t===!1||null===t||void 0===t)return 0;if("function"==typeof t.valueOf&&(t=t.valueOf(),t===!1||null===t||void 0===t))return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if(t!==t||t===1/0)return 0;var r=0|t;for(r!==t&&(r^=4294967295*t);t>4294967295;)t/=4294967295,r^=t;return it(r)}if("string"===e)return t.length>Kr?ut(t):st(t);if("function"==typeof t.hashCode)return t.hashCode();if("object"===e)return at(t);if("function"==typeof t.toString)return st(""+t);throw Error("Value type "+e+" cannot be hashed.")}function ut(t){var e=Br[t];return void 0===e&&(e=st(t),Tr===Lr&&(Tr=0,Br={}),Tr++,Br[t]=e),e}function st(t){for(var e=0,r=0;t.length>r;r++)e=31*e+t.charCodeAt(r)|0;return it(e)}function at(t){var e;if(jr&&(e=Or.get(t),void 0!==e))return e;if(e=t[Ur],void 0!==e)return e;if(!Ar){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[Ur],void 0!==e)return e;if(e=ht(t),void 0!==e)return e}if(e=++Rr,1073741824&Rr&&(Rr=0),jr)Or.set(t,e);else{if(void 0!==kr&&kr(t)===!1)throw Error("Non-extensible objects are not allowed as keys.");
if(Ar)Object.defineProperty(t,Ur,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(void 0!==t.propertyIsEnumerable&&t.propertyIsEnumerable===t.constructor.prototype.propertyIsEnumerable)t.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},t.propertyIsEnumerable[Ur]=e;else{if(void 0===t.nodeType)throw Error("Unable to set a non-enumerable property on object.");t[Ur]=e}}return e}function ht(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}function ft(t){Z(t!==1/0,"Cannot perform this action with an infinite size.")}function ct(t){return null===t||void 0===t?zt():_t(t)&&!h(t)?t:zt().withMutations(function(e){var n=r(t);ft(n.size),n.forEach(function(t,r){return e.set(r,t)})})}function _t(t){return!(!t||!t[Wr])}function pt(t,e){this.ownerID=t,this.entries=e}function vt(t,e,r){this.ownerID=t,this.bitmap=e,this.nodes=r}function lt(t,e,r){this.ownerID=t,this.count=e,this.nodes=r}function yt(t,e,r){this.ownerID=t,this.keyHash=e,this.entries=r}function dt(t,e,r){this.ownerID=t,this.keyHash=e,this.entry=r}function mt(t,e,r){this._type=e,this._reverse=r,this._stack=t._root&&wt(t._root)}function gt(t,e){return z(t,e[0],e[1])}function wt(t,e){return{node:t,index:0,__prev:e}}function St(t,e,r,n){var i=Object.create(Cr);return i.size=t,i._root=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function zt(){return Jr||(Jr=St(0))}function It(t,e,r){var n,i;if(t._root){var o=f(dr),u=f(mr);if(n=bt(t._root,t.__ownerID,0,void 0,e,r,o,u),!u.value)return t;i=t.size+(o.value?r===yr?-1:1:0)}else{if(r===yr)return t;i=1,n=new pt(t.__ownerID,[[e,r]])}return t.__ownerID?(t.size=i,t._root=n,t.__hash=void 0,t.__altered=!0,t):n?St(i,n):zt()}function bt(t,e,r,n,i,o,u,s){return t?t.update(e,r,n,i,o,u,s):o===yr?t:(c(s),c(u),new dt(e,n,[i,o]))}function qt(t){return t.constructor===dt||t.constructor===yt}function Dt(t,e,r,n,i){if(t.keyHash===n)return new yt(e,n,[t.entry,i]);var o,u=(0===r?t.keyHash:t.keyHash>>>r)&lr,s=(0===r?n:n>>>r)&lr,a=u===s?[Dt(t,e,r+pr,n,i)]:(o=new dt(e,n,i),
s>u?[t,o]:[o,t]);return new vt(e,1<<u|1<<s,a)}function Mt(t,e,r,n){t||(t=new _);for(var i=new dt(t,ot(r),[r,n]),o=0;e.length>o;o++){var u=e[o];i=i.update(t,0,void 0,u[0],u[1])}return i}function Et(t,e,r,n){for(var i=0,o=0,u=Array(r),s=0,a=1,h=e.length;h>s;s++,a<<=1){var f=e[s];void 0!==f&&s!==n&&(i|=a,u[o++]=f)}return new vt(t,i,u)}function Ot(t,e,r,n,i){for(var o=0,u=Array(vr),s=0;0!==r;s++,r>>>=1)u[s]=1&r?e[o++]:void 0;return u[n]=i,new lt(t,o+1,u)}function xt(t,e,n){for(var i=[],u=0;n.length>u;u++){var s=n[u],a=r(s);o(s)||(a=a.map(function(t){return H(t)})),i.push(a)}return jt(t,e,i)}function kt(t,e,r){return t&&t.mergeDeep&&o(e)?t.mergeDeep(e):X(t,e)?t:e}function At(t){return function(e,r,n){if(e&&e.mergeDeepWith&&o(r))return e.mergeDeepWith(t,r);var i=t(e,r,n);return X(e,i)?e:i}}function jt(t,e,r){return r=r.filter(function(t){return 0!==t.size}),0===r.length?t:0!==t.size||t.__ownerID||1!==r.length?t.withMutations(function(t){for(var n=e?function(r,n){t.update(n,yr,function(t){return t===yr?r:e(t,r,n)})}:function(e,r){t.set(r,e)},i=0;r.length>i;i++)r[i].forEach(n)}):t.constructor(r[0])}function Rt(t,e,r,n){var i=t===yr,o=e.next();if(o.done){var u=i?r:t,s=n(u);return s===u?t:s}Z(i||t&&t.set,"invalid keyPath");var a=o.value,h=i?yr:t.get(a,yr),f=Rt(h,e,r,n);return f===h?t:f===yr?t.remove(a):(i?zt():t).set(a,f)}function Ut(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function Kt(t,e,r,n){var i=n?t:p(t);return i[e]=r,i}function Lt(t,e,r,n){var i=t.length+1;if(n&&e+1===i)return t[e]=r,t;for(var o=Array(i),u=0,s=0;i>s;s++)s===e?(o[s]=r,u=-1):o[s]=t[s+u];return o}function Tt(t,e,r){var n=t.length-1;if(r&&e===n)return t.pop(),t;for(var i=Array(n),o=0,u=0;n>u;u++)u===e&&(o=1),i[u]=t[u+o];return i}function Bt(t){var e=Pt();if(null===t||void 0===t)return e;if(Wt(t))return t;var r=n(t),i=r.size;return 0===i?e:(ft(i),i>0&&vr>i?Nt(0,i,pr,null,new Ct(r.toArray())):e.withMutations(function(t){t.setSize(i),r.forEach(function(e,r){return t.set(r,e)})}))}function Wt(t){
return!(!t||!t[Vr])}function Ct(t,e){this.array=t,this.ownerID=e}function Jt(t,e){function r(t,e,r){return 0===e?n(t,r):i(t,e,r)}function n(t,r){var n=r===s?a&&a.array:t&&t.array,i=r>o?0:o-r,h=u-r;return h>vr&&(h=vr),function(){if(i===h)return Xr;var t=e?--h:i++;return n&&n[t]}}function i(t,n,i){var s,a=t&&t.array,h=i>o?0:o-i>>n,f=(u-i>>n)+1;return f>vr&&(f=vr),function(){for(;;){if(s){var t=s();if(t!==Xr)return t;s=null}if(h===f)return Xr;var o=e?--f:h++;s=r(a&&a[o],n-pr,i+(o<<n))}}}var o=t._origin,u=t._capacity,s=Gt(u),a=t._tail;return r(t._root,t._level,0)}function Nt(t,e,r,n,i,o,u){var s=Object.create(Yr);return s.size=e-t,s._origin=t,s._capacity=e,s._level=r,s._root=n,s._tail=i,s.__ownerID=o,s.__hash=u,s.__altered=!1,s}function Pt(){return Qr||(Qr=Nt(0,0,pr))}function Ht(t,e,r){if(e=l(t,e),e!==e)return t;if(e>=t.size||0>e)return t.withMutations(function(t){0>e?Xt(t,e).set(0,r):Xt(t,0,e+1).set(e,r)});e+=t._origin;var n=t._tail,i=t._root,o=f(mr);return e>=Gt(t._capacity)?n=Vt(n,t.__ownerID,0,e,r,o):i=Vt(i,t.__ownerID,t._level,e,r,o),o.value?t.__ownerID?(t._root=i,t._tail=n,t.__hash=void 0,t.__altered=!0,t):Nt(t._origin,t._capacity,t._level,i,n):t}function Vt(t,e,r,n,i,o){var u=n>>>r&lr,s=t&&t.array.length>u;if(!s&&void 0===i)return t;var a;if(r>0){var h=t&&t.array[u],f=Vt(h,e,r-pr,n,i,o);return f===h?t:(a=Yt(t,e),a.array[u]=f,a)}return s&&t.array[u]===i?t:(c(o),a=Yt(t,e),void 0===i&&u===a.array.length-1?a.array.pop():a.array[u]=i,a)}function Yt(t,e){return e&&t&&e===t.ownerID?t:new Ct(t?t.array.slice():[],e)}function Qt(t,e){if(e>=Gt(t._capacity))return t._tail;if(1<<t._level+pr>e){for(var r=t._root,n=t._level;r&&n>0;)r=r.array[e>>>n&lr],n-=pr;return r}}function Xt(t,e,r){void 0!==e&&(e=0|e),void 0!==r&&(r=0|r);var n=t.__ownerID||new _,i=t._origin,o=t._capacity,u=i+e,s=void 0===r?o:0>r?o+r:i+r;if(u===i&&s===o)return t;if(u>=s)return t.clear();for(var a=t._level,h=t._root,f=0;0>u+f;)h=new Ct(h&&h.array.length?[void 0,h]:[],n),a+=pr,f+=1<<a;f&&(u+=f,i+=f,s+=f,o+=f);for(var c=Gt(o),p=Gt(s);p>=1<<a+pr;)h=new Ct(h&&h.array.length?[h]:[],n),
a+=pr;var v=t._tail,l=c>p?Qt(t,s-1):p>c?new Ct([],n):v;if(v&&p>c&&o>u&&v.array.length){h=Yt(h,n);for(var y=h,d=a;d>pr;d-=pr){var m=c>>>d&lr;y=y.array[m]=Yt(y.array[m],n)}y.array[c>>>pr&lr]=v}if(o>s&&(l=l&&l.removeAfter(n,0,s)),u>=p)u-=p,s-=p,a=pr,h=null,l=l&&l.removeBefore(n,0,u);else if(u>i||c>p){for(f=0;h;){var g=u>>>a&lr;if(g!==p>>>a&lr)break;g&&(f+=(1<<a)*g),a-=pr,h=h.array[g]}h&&u>i&&(h=h.removeBefore(n,a,u-f)),h&&c>p&&(h=h.removeAfter(n,a,p-f)),f&&(u-=f,s-=f)}return t.__ownerID?(t.size=s-u,t._origin=u,t._capacity=s,t._level=a,t._root=h,t._tail=l,t.__hash=void 0,t.__altered=!0,t):Nt(u,s,a,h,l)}function Ft(t,e,r){for(var i=[],u=0,s=0;r.length>s;s++){var a=r[s],h=n(a);h.size>u&&(u=h.size),o(a)||(h=h.map(function(t){return H(t)})),i.push(h)}return u>t.size&&(t=t.setSize(u)),jt(t,e,i)}function Gt(t){return vr>t?0:t-1>>>pr<<pr}function Zt(t){return null===t||void 0===t?ee():$t(t)?t:ee().withMutations(function(e){var n=r(t);ft(n.size),n.forEach(function(t,r){return e.set(r,t)})})}function $t(t){return _t(t)&&h(t)}function te(t,e,r,n){var i=Object.create(Zt.prototype);return i.size=t?t.size:0,i._map=t,i._list=e,i.__ownerID=r,i.__hash=n,i}function ee(){return Fr||(Fr=te(zt(),Pt()))}function re(t,e,r){var n,i,o=t._map,u=t._list,s=o.get(e),a=void 0!==s;if(r===yr){if(!a)return t;u.size>=vr&&u.size>=2*o.size?(i=u.filter(function(t,e){return void 0!==t&&s!==e}),n=i.toKeyedSeq().map(function(t){return t[0]}).flip().toMap(),t.__ownerID&&(n.__ownerID=i.__ownerID=t.__ownerID)):(n=o.remove(e),i=s===u.size-1?u.pop():u.set(s,void 0))}else if(a){if(r===u.get(s)[1])return t;n=o,i=u.set(s,[e,r])}else n=o.set(e,u.size),i=u.set(u.size,[e,r]);return t.__ownerID?(t.size=n.size,t._map=n,t._list=i,t.__hash=void 0,t):te(n,i)}function ne(t,e){this._iter=t,this._useKeys=e,this.size=t.size}function ie(t){this._iter=t,this.size=t.size}function oe(t){this._iter=t,this.size=t.size}function ue(t){this._iter=t,this.size=t.size}function se(t){var e=Ee(t);return e._iter=t,e.size=t.size,e.flip=function(){return t},e.reverse=function(){var e=t.reverse.apply(this);
return e.flip=function(){return t.reverse()},e},e.has=function(e){return t.includes(e)},e.includes=function(e){return t.has(e)},e.cacheResult=Oe,e.__iterateUncached=function(e,r){var n=this;return t.__iterate(function(t,r){return e(r,t,n)!==!1},r)},e.__iteratorUncached=function(e,r){if(e===Sr){var n=t.__iterator(e,r);return new S(function(){var t=n.next();if(!t.done){var e=t.value[0];t.value[0]=t.value[1],t.value[1]=e}return t})}return t.__iterator(e===wr?gr:wr,r)},e}function ae(t,e,r){var n=Ee(t);return n.size=t.size,n.has=function(e){return t.has(e)},n.get=function(n,i){var o=t.get(n,yr);return o===yr?i:e.call(r,o,n,t)},n.__iterateUncached=function(n,i){var o=this;return t.__iterate(function(t,i,u){return n(e.call(r,t,i,u),i,o)!==!1},i)},n.__iteratorUncached=function(n,i){var o=t.__iterator(Sr,i);return new S(function(){var i=o.next();if(i.done)return i;var u=i.value,s=u[0];return z(n,s,e.call(r,u[1],s,t),i)})},n}function he(t,e){var r=Ee(t);return r._iter=t,r.size=t.size,r.reverse=function(){return t},t.flip&&(r.flip=function(){var e=se(t);return e.reverse=function(){return t.flip()},e}),r.get=function(r,n){return t.get(e?r:-1-r,n)},r.has=function(r){return t.has(e?r:-1-r)},r.includes=function(e){return t.includes(e)},r.cacheResult=Oe,r.__iterate=function(e,r){var n=this;return t.__iterate(function(t,r){return e(t,r,n)},!r)},r.__iterator=function(e,r){return t.__iterator(e,!r)},r}function fe(t,e,r,n){var i=Ee(t);return n&&(i.has=function(n){var i=t.get(n,yr);return i!==yr&&!!e.call(r,i,n,t)},i.get=function(n,i){var o=t.get(n,yr);return o!==yr&&e.call(r,o,n,t)?o:i}),i.__iterateUncached=function(i,o){var u=this,s=0;return t.__iterate(function(t,o,a){return e.call(r,t,o,a)?(s++,i(t,n?o:s-1,u)):void 0},o),s},i.__iteratorUncached=function(i,o){var u=t.__iterator(Sr,o),s=0;return new S(function(){for(;;){var o=u.next();if(o.done)return o;var a=o.value,h=a[0],f=a[1];if(e.call(r,f,h,t))return z(i,n?h:s++,f,o)}})},i}function ce(t,e,r){var n=ct().asMutable();return t.__iterate(function(i,o){n.update(e.call(r,i,o,t),0,function(t){
return t+1})}),n.asImmutable()}function _e(t,e,r){var n=u(t),i=(h(t)?Zt():ct()).asMutable();t.__iterate(function(o,u){i.update(e.call(r,o,u,t),function(t){return t=t||[],t.push(n?[u,o]:o),t})});var o=Me(t);return i.map(function(e){return be(t,o(e))})}function pe(t,e,r,n){var i=t.size;if(void 0!==e&&(e=0|e),void 0!==r&&(r=r===1/0?i:0|r),d(e,r,i))return t;var o=m(e,i),u=g(r,i);if(o!==o||u!==u)return pe(t.toSeq().cacheResult(),e,r,n);var s,a=u-o;a===a&&(s=0>a?0:a);var h=Ee(t);return h.size=0===s?s:t.size&&s||void 0,!n&&L(t)&&s>=0&&(h.get=function(e,r){return e=l(this,e),e>=0&&s>e?t.get(e+o,r):r}),h.__iterateUncached=function(e,r){var i=this;if(0===s)return 0;if(r)return this.cacheResult().__iterate(e,r);var u=0,a=!0,h=0;return t.__iterate(function(t,r){return a&&(a=u++<o)?void 0:(h++,e(t,n?r:h-1,i)!==!1&&h!==s)}),h},h.__iteratorUncached=function(e,r){if(0!==s&&r)return this.cacheResult().__iterator(e,r);var i=0!==s&&t.__iterator(e,r),u=0,a=0;return new S(function(){for(;u++<o;)i.next();if(++a>s)return I();var t=i.next();return n||e===wr?t:e===gr?z(e,a-1,void 0,t):z(e,a-1,t.value[1],t)})},h}function ve(t,e,r){var n=Ee(t);return n.__iterateUncached=function(n,i){var o=this;if(i)return this.cacheResult().__iterate(n,i);var u=0;return t.__iterate(function(t,i,s){return e.call(r,t,i,s)&&++u&&n(t,i,o)}),u},n.__iteratorUncached=function(n,i){var o=this;if(i)return this.cacheResult().__iterator(n,i);var u=t.__iterator(Sr,i),s=!0;return new S(function(){if(!s)return I();var t=u.next();if(t.done)return t;var i=t.value,a=i[0],h=i[1];return e.call(r,h,a,o)?n===Sr?t:z(n,a,h,t):(s=!1,I())})},n}function le(t,e,r,n){var i=Ee(t);return i.__iterateUncached=function(i,o){var u=this;if(o)return this.cacheResult().__iterate(i,o);var s=!0,a=0;return t.__iterate(function(t,o,h){return s&&(s=e.call(r,t,o,h))?void 0:(a++,i(t,n?o:a-1,u))}),a},i.__iteratorUncached=function(i,o){var u=this;if(o)return this.cacheResult().__iterator(i,o);var s=t.__iterator(Sr,o),a=!0,h=0;return new S(function(){var t,o,f;do{if(t=s.next(),t.done)return n||i===wr?t:i===gr?z(i,h++,void 0,t):z(i,h++,t.value[1],t);
var c=t.value;o=c[0],f=c[1],a&&(a=e.call(r,f,o,u))}while(a);return i===Sr?t:z(i,o,f,t)})},i}function ye(t,e){var n=u(t),i=[t].concat(e).map(function(t){return o(t)?n&&(t=r(t)):t=n?B(t):W(Array.isArray(t)?t:[t]),t}).filter(function(t){return 0!==t.size});if(0===i.length)return t;if(1===i.length){var a=i[0];if(a===t||n&&u(a)||s(t)&&s(a))return a}var h=new j(i);return n?h=h.toKeyedSeq():s(t)||(h=h.toSetSeq()),h=h.flatten(!0),h.size=i.reduce(function(t,e){if(void 0!==t){var r=e.size;if(void 0!==r)return t+r}},0),h}function de(t,e,r){var n=Ee(t);return n.__iterateUncached=function(n,i){function u(t,h){var f=this;t.__iterate(function(t,i){return(!e||e>h)&&o(t)?u(t,h+1):n(t,r?i:s++,f)===!1&&(a=!0),!a},i)}var s=0,a=!1;return u(t,0),s},n.__iteratorUncached=function(n,i){var u=t.__iterator(n,i),s=[],a=0;return new S(function(){for(;u;){var t=u.next();if(t.done===!1){var h=t.value;if(n===Sr&&(h=h[1]),e&&!(e>s.length)||!o(h))return r?t:z(n,a++,h,t);s.push(u),u=h.__iterator(n,i)}else u=s.pop()}return I()})},n}function me(t,e,r){var n=Me(t);return t.toSeq().map(function(i,o){return n(e.call(r,i,o,t))}).flatten(!0)}function ge(t,e){var r=Ee(t);return r.size=t.size&&2*t.size-1,r.__iterateUncached=function(r,n){var i=this,o=0;return t.__iterate(function(t,n){return(!o||r(e,o++,i)!==!1)&&r(t,o++,i)!==!1},n),o},r.__iteratorUncached=function(r,n){var i,o=t.__iterator(wr,n),u=0;return new S(function(){return(!i||u%2)&&(i=o.next(),i.done)?i:u%2?z(r,u++,e):z(r,u++,i.value,i)})},r}function we(t,e,r){e||(e=xe);var n=u(t),i=0,o=t.toSeq().map(function(e,n){return[n,e,i++,r?r(e,n,t):e]}).toArray();return o.sort(function(t,r){return e(t[3],r[3])||t[2]-r[2]}).forEach(n?function(t,e){o[e].length=2}:function(t,e){o[e]=t[1]}),n?x(o):s(t)?k(o):A(o)}function Se(t,e,r){if(e||(e=xe),r){var n=t.toSeq().map(function(e,n){return[e,r(e,n,t)]}).reduce(function(t,r){return ze(e,t[1],r[1])?r:t});return n&&n[0]}return t.reduce(function(t,r){return ze(e,t,r)?r:t})}function ze(t,e,r){var n=t(r,e);return 0===n&&r!==e&&(void 0===r||null===r||r!==r)||n>0}function Ie(t,r,n){
var i=Ee(t);return i.size=new j(n).map(function(t){return t.size}).min(),i.__iterate=function(t,e){for(var r,n=this.__iterator(wr,e),i=0;!(r=n.next()).done&&t(r.value,i++,this)!==!1;);return i},i.__iteratorUncached=function(t,i){var o=n.map(function(t){return t=e(t),D(i?t.reverse():t)}),u=0,s=!1;return new S(function(){var e;return s||(e=o.map(function(t){return t.next()}),s=e.some(function(t){return t.done})),s?I():z(t,u++,r.apply(null,e.map(function(t){return t.value})))})},i}function be(t,e){return L(t)?e:t.constructor(e)}function qe(t){if(t!==Object(t))throw new TypeError("Expected [K, V] tuple: "+t)}function De(t){return ft(t.size),v(t)}function Me(t){return u(t)?r:s(t)?n:i}function Ee(t){return Object.create((u(t)?x:s(t)?k:A).prototype)}function Oe(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):O.prototype.cacheResult.call(this)}function xe(t,e){return t>e?1:e>t?-1:0}function ke(t){var r=D(t);if(!r){if(!E(t))throw new TypeError("Expected iterable or array-like: "+t);r=D(e(t))}return r}function Ae(t,e){var r,n=function(o){if(o instanceof n)return o;if(!(this instanceof n))return new n(o);if(!r){r=!0;var u=Object.keys(t);Ue(i,u),i.size=u.length,i._name=e,i._keys=u,i._defaultValues=t}this._map=ct(o)},i=n.prototype=Object.create(Gr);return i.constructor=n,n}function je(t,e,r){var n=Object.create(Object.getPrototypeOf(t));return n._map=e,n.__ownerID=r,n}function Re(t){return t._name||t.constructor.name||"Record"}function Ue(t,e){try{e.forEach(Ke.bind(void 0,t))}catch(r){}}function Ke(t,e){Object.defineProperty(t,e,{get:function(){return this.get(e)},set:function(t){Z(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}function Le(t){return null===t||void 0===t?Ce():Te(t)&&!h(t)?t:Ce().withMutations(function(e){var r=i(t);ft(r.size),r.forEach(function(t){return e.add(t)})})}function Te(t){return!(!t||!t[Zr])}function Be(t,e){return t.__ownerID?(t.size=e.size,t._map=e,t):e===t._map?t:0===e.size?t.__empty():t.__make(e)}function We(t,e){var r=Object.create($r);
return r.size=t?t.size:0,r._map=t,r.__ownerID=e,r}function Ce(){return tn||(tn=We(zt()))}function Je(t){return null===t||void 0===t?He():Ne(t)?t:He().withMutations(function(e){var r=i(t);ft(r.size),r.forEach(function(t){return e.add(t)})})}function Ne(t){return Te(t)&&h(t)}function Pe(t,e){var r=Object.create(en);return r.size=t?t.size:0,r._map=t,r.__ownerID=e,r}function He(){return rn||(rn=Pe(ee()))}function Ve(t){return null===t||void 0===t?Xe():Ye(t)?t:Xe().unshiftAll(t)}function Ye(t){return!(!t||!t[nn])}function Qe(t,e,r,n){var i=Object.create(on);return i.size=t,i._head=e,i.__ownerID=r,i.__hash=n,i.__altered=!1,i}function Xe(){return un||(un=Qe(0))}function Fe(t,e){var r=function(r){t.prototype[r]=e[r]};return Object.keys(e).forEach(r),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(e).forEach(r),t}function Ge(t,e){return e}function Ze(t,e){return[e,t]}function $e(t){return function(){return!t.apply(this,arguments)}}function tr(t){return function(){return-t.apply(this,arguments)}}function er(t){return"string"==typeof t?JSON.stringify(t):t+""}function rr(){return p(arguments)}function nr(t,e){return e>t?1:t>e?-1:0}function ir(t){if(t.size===1/0)return 0;var e=h(t),r=u(t),n=e?1:0,i=t.__iterate(r?e?function(t,e){n=31*n+ur(ot(t),ot(e))|0}:function(t,e){n=n+ur(ot(t),ot(e))|0}:e?function(t){n=31*n+ot(t)|0}:function(t){n=n+ot(t)|0});return or(i,n)}function or(t,e){return e=xr(e,3432918353),e=xr(e<<15|e>>>-15,461845907),e=xr(e<<13|e>>>-13,5),e=(e+3864292196|0)^t,e=xr(e^e>>>16,2246822507),e=xr(e^e>>>13,3266489909),e=it(e^e>>>16)}function ur(t,e){return t^e+2654435769+(t<<6)+(t>>2)|0}var sr=Array.prototype.slice;t(r,e),t(n,e),t(i,e),e.isIterable=o,e.isKeyed=u,e.isIndexed=s,e.isAssociative=a,e.isOrdered=h,e.Keyed=r,e.Indexed=n,e.Set=i;var ar="@@__IMMUTABLE_ITERABLE__@@",hr="@@__IMMUTABLE_KEYED__@@",fr="@@__IMMUTABLE_INDEXED__@@",cr="@@__IMMUTABLE_ORDERED__@@",_r="delete",pr=5,vr=1<<pr,lr=vr-1,yr={},dr={value:!1},mr={value:!1},gr=0,wr=1,Sr=2,zr="function"==typeof Symbol&&Symbol.iterator,Ir="@@iterator",br=zr||Ir;
S.prototype.toString=function(){return"[Iterator]"},S.KEYS=gr,S.VALUES=wr,S.ENTRIES=Sr,S.prototype.inspect=S.prototype.toSource=function(){return""+this},S.prototype[br]=function(){return this},t(O,e),O.of=function(){return O(arguments)},O.prototype.toSeq=function(){return this},O.prototype.toString=function(){return this.__toString("Seq {","}")},O.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},O.prototype.__iterate=function(t,e){return N(this,t,e,!0)},O.prototype.__iterator=function(t,e){return P(this,t,e,!0)},t(x,O),x.prototype.toKeyedSeq=function(){return this},t(k,O),k.of=function(){return k(arguments)},k.prototype.toIndexedSeq=function(){return this},k.prototype.toString=function(){return this.__toString("Seq [","]")},k.prototype.__iterate=function(t,e){return N(this,t,e,!1)},k.prototype.__iterator=function(t,e){return P(this,t,e,!1)},t(A,O),A.of=function(){return A(arguments)},A.prototype.toSetSeq=function(){return this},O.isSeq=L,O.Keyed=x,O.Set=A,O.Indexed=k;var qr="@@__IMMUTABLE_SEQ__@@";O.prototype[qr]=!0,t(j,k),j.prototype.get=function(t,e){return this.has(t)?this._array[l(this,t)]:e},j.prototype.__iterate=function(t,e){for(var r=this._array,n=r.length-1,i=0;n>=i;i++)if(t(r[e?n-i:i],i,this)===!1)return i+1;return i},j.prototype.__iterator=function(t,e){var r=this._array,n=r.length-1,i=0;return new S(function(){return i>n?I():z(t,i,r[e?n-i++:i++])})},t(R,x),R.prototype.get=function(t,e){return void 0===e||this.has(t)?this._object[t]:e},R.prototype.has=function(t){return this._object.hasOwnProperty(t)},R.prototype.__iterate=function(t,e){for(var r=this._object,n=this._keys,i=n.length-1,o=0;i>=o;o++){var u=n[e?i-o:o];if(t(r[u],u,this)===!1)return o+1}return o},R.prototype.__iterator=function(t,e){var r=this._object,n=this._keys,i=n.length-1,o=0;return new S(function(){var u=n[e?i-o:o];return o++>i?I():z(t,u,r[u])})},R.prototype[cr]=!0,t(U,k),U.prototype.__iterateUncached=function(t,e){if(e)return this.cacheResult().__iterate(t,e);
var r=this._iterable,n=D(r),i=0;if(q(n))for(var o;!(o=n.next()).done&&t(o.value,i++,this)!==!1;);return i},U.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterable,n=D(r);if(!q(n))return new S(I);var i=0;return new S(function(){var e=n.next();return e.done?e:z(t,i++,e.value)})},t(K,k),K.prototype.__iterateUncached=function(t,e){if(e)return this.cacheResult().__iterate(t,e);for(var r=this._iterator,n=this._iteratorCache,i=0;n.length>i;)if(t(n[i],i++,this)===!1)return i;for(var o;!(o=r.next()).done;){var u=o.value;if(n[i]=u,t(u,i++,this)===!1)break}return i},K.prototype.__iteratorUncached=function(t,e){if(e)return this.cacheResult().__iterator(t,e);var r=this._iterator,n=this._iteratorCache,i=0;return new S(function(){if(i>=n.length){var e=r.next();if(e.done)return e;n[i]=e.value}return z(t,i,n[i++])})};var Dr;t(G,k),G.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},G.prototype.get=function(t,e){return this.has(t)?this._value:e},G.prototype.includes=function(t){return X(this._value,t)},G.prototype.slice=function(t,e){var r=this.size;return d(t,e,r)?this:new G(this._value,g(e,r)-m(t,r))},G.prototype.reverse=function(){return this},G.prototype.indexOf=function(t){return X(this._value,t)?0:-1},G.prototype.lastIndexOf=function(t){return X(this._value,t)?this.size:-1},G.prototype.__iterate=function(t,e){for(var r=0;this.size>r;r++)if(t(this._value,r,this)===!1)return r+1;return r},G.prototype.__iterator=function(t,e){var r=this,n=0;return new S(function(){return r.size>n?z(t,n++,r._value):I()})},G.prototype.equals=function(t){return t instanceof G?X(this._value,t._value):F(t)};var Mr;t($,k),$.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(1!==this._step?" by "+this._step:"")+" ]"},$.prototype.get=function(t,e){return this.has(t)?this._start+l(this,t)*this._step:e},$.prototype.includes=function(t){var e=(t-this._start)/this._step;return e>=0&&this.size>e&&e===Math.floor(e);
},$.prototype.slice=function(t,e){return d(t,e,this.size)?this:(t=m(t,this.size),e=g(e,this.size),t>=e?new $(0,0):new $(this.get(t,this._end),this.get(e,this._end),this._step))},$.prototype.indexOf=function(t){var e=t-this._start;if(e%this._step===0){var r=e/this._step;if(r>=0&&this.size>r)return r}return-1},$.prototype.lastIndexOf=function(t){return this.indexOf(t)},$.prototype.__iterate=function(t,e){for(var r=this.size-1,n=this._step,i=e?this._start+r*n:this._start,o=0;r>=o;o++){if(t(i,o,this)===!1)return o+1;i+=e?-n:n}return o},$.prototype.__iterator=function(t,e){var r=this.size-1,n=this._step,i=e?this._start+r*n:this._start,o=0;return new S(function(){var u=i;return i+=e?-n:n,o>r?I():z(t,o++,u)})},$.prototype.equals=function(t){return t instanceof $?this._start===t._start&&this._end===t._end&&this._step===t._step:F(this,t)};var Er;t(tt,e),t(et,tt),t(rt,tt),t(nt,tt),tt.Keyed=et,tt.Indexed=rt,tt.Set=nt;var Or,xr="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(t,e){t=0|t,e=0|e;var r=65535&t,n=65535&e;return r*n+((t>>>16)*n+r*(e>>>16)<<16>>>0)|0},kr=Object.isExtensible,Ar=function(){try{return Object.defineProperty({},"@",{}),!0}catch(t){return!1}}(),jr="function"==typeof WeakMap;jr&&(Or=new WeakMap);var Rr=0,Ur="__immutablehash__";"function"==typeof Symbol&&(Ur=Symbol(Ur));var Kr=16,Lr=255,Tr=0,Br={};t(ct,et),ct.of=function(){var t=sr.call(arguments,0);return zt().withMutations(function(e){for(var r=0;t.length>r;r+=2){if(r+1>=t.length)throw Error("Missing value for key: "+t[r]);e.set(t[r],t[r+1])}})},ct.prototype.toString=function(){return this.__toString("Map {","}")},ct.prototype.get=function(t,e){return this._root?this._root.get(0,void 0,t,e):e},ct.prototype.set=function(t,e){return It(this,t,e)},ct.prototype.setIn=function(t,e){return this.updateIn(t,yr,function(){return e})},ct.prototype.remove=function(t){return It(this,t,yr)},ct.prototype.deleteIn=function(t){return this.updateIn(t,function(){return yr})},ct.prototype.update=function(t,e,r){return 1===arguments.length?t(this):this.updateIn([t],e,r);
},ct.prototype.updateIn=function(t,e,r){r||(r=e,e=void 0);var n=Rt(this,ke(t),e,r);return n===yr?void 0:n},ct.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):zt()},ct.prototype.merge=function(){return xt(this,void 0,arguments)},ct.prototype.mergeWith=function(t){var e=sr.call(arguments,1);return xt(this,t,e)},ct.prototype.mergeIn=function(t){var e=sr.call(arguments,1);return this.updateIn(t,zt(),function(t){return"function"==typeof t.merge?t.merge.apply(t,e):e[e.length-1]})},ct.prototype.mergeDeep=function(){return xt(this,kt,arguments)},ct.prototype.mergeDeepWith=function(t){var e=sr.call(arguments,1);return xt(this,At(t),e)},ct.prototype.mergeDeepIn=function(t){var e=sr.call(arguments,1);return this.updateIn(t,zt(),function(t){return"function"==typeof t.mergeDeep?t.mergeDeep.apply(t,e):e[e.length-1]})},ct.prototype.sort=function(t){return Zt(we(this,t))},ct.prototype.sortBy=function(t,e){return Zt(we(this,e,t))},ct.prototype.withMutations=function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},ct.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new _)},ct.prototype.asImmutable=function(){return this.__ensureOwner()},ct.prototype.wasAltered=function(){return this.__altered},ct.prototype.__iterator=function(t,e){return new mt(this,t,e)},ct.prototype.__iterate=function(t,e){var r=this,n=0;return this._root&&this._root.iterate(function(e){return n++,t(e[1],e[0],r)},e),n},ct.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?St(this.size,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},ct.isMap=_t;var Wr="@@__IMMUTABLE_MAP__@@",Cr=ct.prototype;Cr[Wr]=!0,Cr[_r]=Cr.remove,Cr.removeIn=Cr.deleteIn,pt.prototype.get=function(t,e,r,n){for(var i=this.entries,o=0,u=i.length;u>o;o++)if(X(r,i[o][0]))return i[o][1];return n},pt.prototype.update=function(t,e,r,n,i,o,u){for(var s=i===yr,a=this.entries,h=0,f=a.length;f>h&&!X(n,a[h][0]);h++);
var _=f>h;if(_?a[h][1]===i:s)return this;if(c(u),(s||!_)&&c(o),!s||1!==a.length){if(!_&&!s&&a.length>=Nr)return Mt(t,a,n,i);var v=t&&t===this.ownerID,l=v?a:p(a);return _?s?h===f-1?l.pop():l[h]=l.pop():l[h]=[n,i]:l.push([n,i]),v?(this.entries=l,this):new pt(t,l)}},vt.prototype.get=function(t,e,r,n){void 0===e&&(e=ot(r));var i=1<<((0===t?e:e>>>t)&lr),o=this.bitmap;return 0===(o&i)?n:this.nodes[Ut(o&i-1)].get(t+pr,e,r,n)},vt.prototype.update=function(t,e,r,n,i,o,u){void 0===r&&(r=ot(n));var s=(0===e?r:r>>>e)&lr,a=1<<s,h=this.bitmap,f=0!==(h&a);if(!f&&i===yr)return this;var c=Ut(h&a-1),_=this.nodes,p=f?_[c]:void 0,v=bt(p,t,e+pr,r,n,i,o,u);if(v===p)return this;if(!f&&v&&_.length>=Pr)return Ot(t,_,h,s,v);if(f&&!v&&2===_.length&&qt(_[1^c]))return _[1^c];if(f&&v&&1===_.length&&qt(v))return v;var l=t&&t===this.ownerID,y=f?v?h:h^a:h|a,d=f?v?Kt(_,c,v,l):Tt(_,c,l):Lt(_,c,v,l);return l?(this.bitmap=y,this.nodes=d,this):new vt(t,y,d)},lt.prototype.get=function(t,e,r,n){void 0===e&&(e=ot(r));var i=(0===t?e:e>>>t)&lr,o=this.nodes[i];return o?o.get(t+pr,e,r,n):n},lt.prototype.update=function(t,e,r,n,i,o,u){void 0===r&&(r=ot(n));var s=(0===e?r:r>>>e)&lr,a=i===yr,h=this.nodes,f=h[s];if(a&&!f)return this;var c=bt(f,t,e+pr,r,n,i,o,u);if(c===f)return this;var _=this.count;if(f){if(!c&&(_--,Hr>_))return Et(t,h,_,s)}else _++;var p=t&&t===this.ownerID,v=Kt(h,s,c,p);return p?(this.count=_,this.nodes=v,this):new lt(t,_,v)},yt.prototype.get=function(t,e,r,n){for(var i=this.entries,o=0,u=i.length;u>o;o++)if(X(r,i[o][0]))return i[o][1];return n},yt.prototype.update=function(t,e,r,n,i,o,u){void 0===r&&(r=ot(n));var s=i===yr;if(r!==this.keyHash)return s?this:(c(u),c(o),Dt(this,t,e,r,[n,i]));for(var a=this.entries,h=0,f=a.length;f>h&&!X(n,a[h][0]);h++);var _=f>h;if(_?a[h][1]===i:s)return this;if(c(u),(s||!_)&&c(o),s&&2===f)return new dt(t,this.keyHash,a[1^h]);var v=t&&t===this.ownerID,l=v?a:p(a);return _?s?h===f-1?l.pop():l[h]=l.pop():l[h]=[n,i]:l.push([n,i]),v?(this.entries=l,this):new yt(t,this.keyHash,l)},dt.prototype.get=function(t,e,r,n){return X(r,this.entry[0])?this.entry[1]:n;
},dt.prototype.update=function(t,e,r,n,i,o,u){var s=i===yr,a=X(n,this.entry[0]);return(a?i===this.entry[1]:s)?this:(c(u),s?void c(o):a?t&&t===this.ownerID?(this.entry[1]=i,this):new dt(t,this.keyHash,[n,i]):(c(o),Dt(this,t,e,ot(n),[n,i])))},pt.prototype.iterate=yt.prototype.iterate=function(t,e){for(var r=this.entries,n=0,i=r.length-1;i>=n;n++)if(t(r[e?i-n:n])===!1)return!1},vt.prototype.iterate=lt.prototype.iterate=function(t,e){for(var r=this.nodes,n=0,i=r.length-1;i>=n;n++){var o=r[e?i-n:n];if(o&&o.iterate(t,e)===!1)return!1}},dt.prototype.iterate=function(t,e){return t(this.entry)},t(mt,S),mt.prototype.next=function(){for(var t=this._type,e=this._stack;e;){var r,n=e.node,i=e.index++;if(n.entry){if(0===i)return gt(t,n.entry)}else if(n.entries){if(r=n.entries.length-1,r>=i)return gt(t,n.entries[this._reverse?r-i:i])}else if(r=n.nodes.length-1,r>=i){var o=n.nodes[this._reverse?r-i:i];if(o){if(o.entry)return gt(t,o.entry);e=this._stack=wt(o,e)}continue}e=this._stack=this._stack.__prev}return I()};var Jr,Nr=vr/4,Pr=vr/2,Hr=vr/4;t(Bt,rt),Bt.of=function(){return this(arguments)},Bt.prototype.toString=function(){return this.__toString("List [","]")},Bt.prototype.get=function(t,e){if(t=l(this,t),t>=0&&this.size>t){t+=this._origin;var r=Qt(this,t);return r&&r.array[t&lr]}return e},Bt.prototype.set=function(t,e){return Ht(this,t,e)},Bt.prototype.remove=function(t){return this.has(t)?0===t?this.shift():t===this.size-1?this.pop():this.splice(t,1):this},Bt.prototype.insert=function(t,e){return this.splice(t,0,e)},Bt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=pr,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):Pt()},Bt.prototype.push=function(){var t=arguments,e=this.size;return this.withMutations(function(r){Xt(r,0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},Bt.prototype.pop=function(){return Xt(this,0,-1)},Bt.prototype.unshift=function(){var t=arguments;return this.withMutations(function(e){Xt(e,-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r]);
})},Bt.prototype.shift=function(){return Xt(this,1)},Bt.prototype.merge=function(){return Ft(this,void 0,arguments)},Bt.prototype.mergeWith=function(t){var e=sr.call(arguments,1);return Ft(this,t,e)},Bt.prototype.mergeDeep=function(){return Ft(this,kt,arguments)},Bt.prototype.mergeDeepWith=function(t){var e=sr.call(arguments,1);return Ft(this,At(t),e)},Bt.prototype.setSize=function(t){return Xt(this,0,t)},Bt.prototype.slice=function(t,e){var r=this.size;return d(t,e,r)?this:Xt(this,m(t,r),g(e,r))},Bt.prototype.__iterator=function(t,e){var r=0,n=Jt(this,e);return new S(function(){var e=n();return e===Xr?I():z(t,r++,e)})},Bt.prototype.__iterate=function(t,e){for(var r,n=0,i=Jt(this,e);(r=i())!==Xr&&t(r,n++,this)!==!1;);return n},Bt.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?Nt(this._origin,this._capacity,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)},Bt.isList=Wt;var Vr="@@__IMMUTABLE_LIST__@@",Yr=Bt.prototype;Yr[Vr]=!0,Yr[_r]=Yr.remove,Yr.setIn=Cr.setIn,Yr.deleteIn=Yr.removeIn=Cr.removeIn,Yr.update=Cr.update,Yr.updateIn=Cr.updateIn,Yr.mergeIn=Cr.mergeIn,Yr.mergeDeepIn=Cr.mergeDeepIn,Yr.withMutations=Cr.withMutations,Yr.asMutable=Cr.asMutable,Yr.asImmutable=Cr.asImmutable,Yr.wasAltered=Cr.wasAltered,Ct.prototype.removeBefore=function(t,e,r){if(r===e?1<<e:0===this.array.length)return this;var n=r>>>e&lr;if(n>=this.array.length)return new Ct([],t);var i,o=0===n;if(e>0){var u=this.array[n];if(i=u&&u.removeBefore(t,e-pr,r),i===u&&o)return this}if(o&&!i)return this;var s=Yt(this,t);if(!o)for(var a=0;n>a;a++)s.array[a]=void 0;return i&&(s.array[n]=i),s},Ct.prototype.removeAfter=function(t,e,r){if(r===(e?1<<e:0)||0===this.array.length)return this;var n=r-1>>>e&lr;if(n>=this.array.length)return this;var i;if(e>0){var o=this.array[n];if(i=o&&o.removeAfter(t,e-pr,r),i===o&&n===this.array.length-1)return this}var u=Yt(this,t);return u.array.splice(n+1),i&&(u.array[n]=i),u};var Qr,Xr={};t(Zt,ct),Zt.of=function(){return this(arguments)},Zt.prototype.toString=function(){return this.__toString("OrderedMap {","}");
},Zt.prototype.get=function(t,e){var r=this._map.get(t);return void 0!==r?this._list.get(r)[1]:e},Zt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):ee()},Zt.prototype.set=function(t,e){return re(this,t,e)},Zt.prototype.remove=function(t){return re(this,t,yr)},Zt.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},Zt.prototype.__iterate=function(t,e){var r=this;return this._list.__iterate(function(e){return e&&t(e[1],e[0],r)},e)},Zt.prototype.__iterator=function(t,e){return this._list.fromEntrySeq().__iterator(t,e)},Zt.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),r=this._list.__ensureOwner(t);return t?te(e,r,t,this.__hash):(this.__ownerID=t,this._map=e,this._list=r,this)},Zt.isOrderedMap=$t,Zt.prototype[cr]=!0,Zt.prototype[_r]=Zt.prototype.remove;var Fr;t(ne,x),ne.prototype.get=function(t,e){return this._iter.get(t,e)},ne.prototype.has=function(t){return this._iter.has(t)},ne.prototype.valueSeq=function(){return this._iter.valueSeq()},ne.prototype.reverse=function(){var t=this,e=he(this,!0);return this._useKeys||(e.valueSeq=function(){return t._iter.toSeq().reverse()}),e},ne.prototype.map=function(t,e){var r=this,n=ae(this,t,e);return this._useKeys||(n.valueSeq=function(){return r._iter.toSeq().map(t,e)}),n},ne.prototype.__iterate=function(t,e){var r,n=this;return this._iter.__iterate(this._useKeys?function(e,r){return t(e,r,n)}:(r=e?De(this):0,function(i){return t(i,e?--r:r++,n)}),e)},ne.prototype.__iterator=function(t,e){if(this._useKeys)return this._iter.__iterator(t,e);var r=this._iter.__iterator(wr,e),n=e?De(this):0;return new S(function(){var i=r.next();return i.done?i:z(t,e?--n:n++,i.value,i)})},ne.prototype[cr]=!0,t(ie,k),ie.prototype.includes=function(t){return this._iter.includes(t)},ie.prototype.__iterate=function(t,e){var r=this,n=0;return this._iter.__iterate(function(e){return t(e,n++,r)},e)},ie.prototype.__iterator=function(t,e){var r=this._iter.__iterator(wr,e),n=0;
return new S(function(){var e=r.next();return e.done?e:z(t,n++,e.value,e)})},t(oe,A),oe.prototype.has=function(t){return this._iter.includes(t)},oe.prototype.__iterate=function(t,e){var r=this;return this._iter.__iterate(function(e){return t(e,e,r)},e)},oe.prototype.__iterator=function(t,e){var r=this._iter.__iterator(wr,e);return new S(function(){var e=r.next();return e.done?e:z(t,e.value,e.value,e)})},t(ue,x),ue.prototype.entrySeq=function(){return this._iter.toSeq()},ue.prototype.__iterate=function(t,e){var r=this;return this._iter.__iterate(function(e){if(e){qe(e);var n=o(e);return t(n?e.get(1):e[1],n?e.get(0):e[0],r)}},e)},ue.prototype.__iterator=function(t,e){var r=this._iter.__iterator(wr,e);return new S(function(){for(;;){var e=r.next();if(e.done)return e;var n=e.value;if(n){qe(n);var i=o(n);return z(t,i?n.get(0):n[0],i?n.get(1):n[1],e)}}})},ie.prototype.cacheResult=ne.prototype.cacheResult=oe.prototype.cacheResult=ue.prototype.cacheResult=Oe,t(Ae,et),Ae.prototype.toString=function(){return this.__toString(Re(this)+" {","}")},Ae.prototype.has=function(t){return this._defaultValues.hasOwnProperty(t)},Ae.prototype.get=function(t,e){if(!this.has(t))return e;var r=this._defaultValues[t];return this._map?this._map.get(t,r):r},Ae.prototype.clear=function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var t=this.constructor;return t._empty||(t._empty=je(this,zt()))},Ae.prototype.set=function(t,e){if(!this.has(t))throw Error('Cannot set unknown key "'+t+'" on '+Re(this));if(this._map&&!this._map.has(t)){var r=this._defaultValues[t];if(e===r)return this}var n=this._map&&this._map.set(t,e);return this.__ownerID||n===this._map?this:je(this,n)},Ae.prototype.remove=function(t){if(!this.has(t))return this;var e=this._map&&this._map.remove(t);return this.__ownerID||e===this._map?this:je(this,e)},Ae.prototype.wasAltered=function(){return this._map.wasAltered()},Ae.prototype.__iterator=function(t,e){var n=this;return r(this._defaultValues).map(function(t,e){return n.get(e)}).__iterator(t,e)},Ae.prototype.__iterate=function(t,e){
var n=this;return r(this._defaultValues).map(function(t,e){return n.get(e)}).__iterate(t,e)},Ae.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?je(this,e,t):(this.__ownerID=t,this._map=e,this)};var Gr=Ae.prototype;Gr[_r]=Gr.remove,Gr.deleteIn=Gr.removeIn=Cr.removeIn,Gr.merge=Cr.merge,Gr.mergeWith=Cr.mergeWith,Gr.mergeIn=Cr.mergeIn,Gr.mergeDeep=Cr.mergeDeep,Gr.mergeDeepWith=Cr.mergeDeepWith,Gr.mergeDeepIn=Cr.mergeDeepIn,Gr.setIn=Cr.setIn,Gr.update=Cr.update,Gr.updateIn=Cr.updateIn,Gr.withMutations=Cr.withMutations,Gr.asMutable=Cr.asMutable,Gr.asImmutable=Cr.asImmutable,t(Le,nt),Le.of=function(){return this(arguments)},Le.fromKeys=function(t){return this(r(t).keySeq())},Le.prototype.toString=function(){return this.__toString("Set {","}")},Le.prototype.has=function(t){return this._map.has(t)},Le.prototype.add=function(t){return Be(this,this._map.set(t,!0))},Le.prototype.remove=function(t){return Be(this,this._map.remove(t))},Le.prototype.clear=function(){return Be(this,this._map.clear())},Le.prototype.union=function(){var t=sr.call(arguments,0);return t=t.filter(function(t){return 0!==t.size}),0===t.length?this:0!==this.size||this.__ownerID||1!==t.length?this.withMutations(function(e){for(var r=0;t.length>r;r++)i(t[r]).forEach(function(t){return e.add(t)})}):this.constructor(t[0])},Le.prototype.intersect=function(){var t=sr.call(arguments,0);if(0===t.length)return this;t=t.map(function(t){return i(t)});var e=this;return this.withMutations(function(r){e.forEach(function(e){t.every(function(t){return t.includes(e)})||r.remove(e)})})},Le.prototype.subtract=function(){var t=sr.call(arguments,0);if(0===t.length)return this;t=t.map(function(t){return i(t)});var e=this;return this.withMutations(function(r){e.forEach(function(e){t.some(function(t){return t.includes(e)})&&r.remove(e)})})},Le.prototype.merge=function(){return this.union.apply(this,arguments)},Le.prototype.mergeWith=function(t){var e=sr.call(arguments,1);return this.union.apply(this,e)},
Le.prototype.sort=function(t){return Je(we(this,t))},Le.prototype.sortBy=function(t,e){return Je(we(this,e,t))},Le.prototype.wasAltered=function(){return this._map.wasAltered()},Le.prototype.__iterate=function(t,e){var r=this;return this._map.__iterate(function(e,n){return t(n,n,r)},e)},Le.prototype.__iterator=function(t,e){return this._map.map(function(t,e){return e}).__iterator(t,e)},Le.prototype.__ensureOwner=function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?this.__make(e,t):(this.__ownerID=t,this._map=e,this)},Le.isSet=Te;var Zr="@@__IMMUTABLE_SET__@@",$r=Le.prototype;$r[Zr]=!0,$r[_r]=$r.remove,$r.mergeDeep=$r.merge,$r.mergeDeepWith=$r.mergeWith,$r.withMutations=Cr.withMutations,$r.asMutable=Cr.asMutable,$r.asImmutable=Cr.asImmutable,$r.__empty=Ce,$r.__make=We;var tn;t(Je,Le),Je.of=function(){return this(arguments)},Je.fromKeys=function(t){return this(r(t).keySeq())},Je.prototype.toString=function(){return this.__toString("OrderedSet {","}")},Je.isOrderedSet=Ne;var en=Je.prototype;en[cr]=!0,en.__empty=He,en.__make=Pe;var rn;t(Ve,rt),Ve.of=function(){return this(arguments)},Ve.prototype.toString=function(){return this.__toString("Stack [","]")},Ve.prototype.get=function(t,e){var r=this._head;for(t=l(this,t);r&&t--;)r=r.next;return r?r.value:e},Ve.prototype.peek=function(){return this._head&&this._head.value},Ve.prototype.push=function(){if(0===arguments.length)return this;for(var t=this.size+arguments.length,e=this._head,r=arguments.length-1;r>=0;r--)e={value:arguments[r],next:e};return this.__ownerID?(this.size=t,this._head=e,this.__hash=void 0,this.__altered=!0,this):Qe(t,e)},Ve.prototype.pushAll=function(t){if(t=n(t),0===t.size)return this;ft(t.size);var e=this.size,r=this._head;return t.reverse().forEach(function(t){e++,r={value:t,next:r}}),this.__ownerID?(this.size=e,this._head=r,this.__hash=void 0,this.__altered=!0,this):Qe(e,r)},Ve.prototype.pop=function(){return this.slice(1)},Ve.prototype.unshift=function(){return this.push.apply(this,arguments)},Ve.prototype.unshiftAll=function(t){
return this.pushAll(t)},Ve.prototype.shift=function(){return this.pop.apply(this,arguments)},Ve.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Xe()},Ve.prototype.slice=function(t,e){if(d(t,e,this.size))return this;var r=m(t,this.size),n=g(e,this.size);if(n!==this.size)return rt.prototype.slice.call(this,t,e);for(var i=this.size-r,o=this._head;r--;)o=o.next;return this.__ownerID?(this.size=i,this._head=o,this.__hash=void 0,this.__altered=!0,this):Qe(i,o)},Ve.prototype.__ensureOwner=function(t){return t===this.__ownerID?this:t?Qe(this.size,this._head,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)},Ve.prototype.__iterate=function(t,e){if(e)return this.reverse().__iterate(t);for(var r=0,n=this._head;n&&t(n.value,r++,this)!==!1;)n=n.next;return r},Ve.prototype.__iterator=function(t,e){if(e)return this.reverse().__iterator(t);var r=0,n=this._head;return new S(function(){if(n){var e=n.value;return n=n.next,z(t,r++,e)}return I()})},Ve.isStack=Ye;var nn="@@__IMMUTABLE_STACK__@@",on=Ve.prototype;on[nn]=!0,on.withMutations=Cr.withMutations,on.asMutable=Cr.asMutable,on.asImmutable=Cr.asImmutable,on.wasAltered=Cr.wasAltered;var un;e.Iterator=S,Fe(e,{toArray:function(){ft(this.size);var t=Array(this.size||0);return this.valueSeq().__iterate(function(e,r){t[r]=e}),t},toIndexedSeq:function(){return new ie(this)},toJS:function(){return this.toSeq().map(function(t){return t&&"function"==typeof t.toJS?t.toJS():t}).__toJS()},toJSON:function(){return this.toSeq().map(function(t){return t&&"function"==typeof t.toJSON?t.toJSON():t}).__toJS()},toKeyedSeq:function(){return new ne(this,!0)},toMap:function(){return ct(this.toKeyedSeq())},toObject:function(){ft(this.size);var t={};return this.__iterate(function(e,r){t[r]=e}),t},toOrderedMap:function(){return Zt(this.toKeyedSeq())},toOrderedSet:function(){return Je(u(this)?this.valueSeq():this)},toSet:function(){return Le(u(this)?this.valueSeq():this)},toSetSeq:function(){return new oe(this);
},toSeq:function(){return s(this)?this.toIndexedSeq():u(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Ve(u(this)?this.valueSeq():this)},toList:function(){return Bt(u(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(t,e){return 0===this.size?t+e:t+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+e},concat:function(){var t=sr.call(arguments,0);return be(this,ye(this,t))},includes:function(t){return this.some(function(e){return X(e,t)})},entries:function(){return this.__iterator(Sr)},every:function(t,e){ft(this.size);var r=!0;return this.__iterate(function(n,i,o){return t.call(e,n,i,o)?void 0:(r=!1,!1)}),r},filter:function(t,e){return be(this,fe(this,t,e,!0))},find:function(t,e,r){var n=this.findEntry(t,e);return n?n[1]:r},forEach:function(t,e){return ft(this.size),this.__iterate(e?t.bind(e):t)},join:function(t){ft(this.size),t=void 0!==t?""+t:",";var e="",r=!0;return this.__iterate(function(n){r?r=!1:e+=t,e+=null!==n&&void 0!==n?""+n:""}),e},keys:function(){return this.__iterator(gr)},map:function(t,e){return be(this,ae(this,t,e))},reduce:function(t,e,r){ft(this.size);var n,i;return arguments.length<2?i=!0:n=e,this.__iterate(function(e,o,u){i?(i=!1,n=e):n=t.call(r,n,e,o,u)}),n},reduceRight:function(t,e,r){var n=this.toKeyedSeq().reverse();return n.reduce.apply(n,arguments)},reverse:function(){return be(this,he(this,!0))},slice:function(t,e){return be(this,pe(this,t,e,!0))},some:function(t,e){return!this.every($e(t),e)},sort:function(t){return be(this,we(this,t))},values:function(){return this.__iterator(wr)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(t,e){return v(t?this.toSeq().filter(t,e):this)},countBy:function(t,e){return ce(this,t,e)},equals:function(t){return F(this,t)},entrySeq:function(){var t=this;if(t._cache)return new j(t._cache);var e=t.toSeq().map(Ze).toIndexedSeq();return e.fromEntrySeq=function(){return t.toSeq()},e},filterNot:function(t,e){
return this.filter($e(t),e)},findEntry:function(t,e,r){var n=r;return this.__iterate(function(r,i,o){return t.call(e,r,i,o)?(n=[i,r],!1):void 0}),n},findKey:function(t,e){var r=this.findEntry(t,e);return r&&r[0]},findLast:function(t,e,r){return this.toKeyedSeq().reverse().find(t,e,r)},findLastEntry:function(t,e,r){return this.toKeyedSeq().reverse().findEntry(t,e,r)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},first:function(){return this.find(y)},flatMap:function(t,e){return be(this,me(this,t,e))},flatten:function(t){return be(this,de(this,t,!0))},fromEntrySeq:function(){return new ue(this)},get:function(t,e){return this.find(function(e,r){return X(r,t)},void 0,e)},getIn:function(t,e){for(var r,n=this,i=ke(t);!(r=i.next()).done;){var o=r.value;if(n=n&&n.get?n.get(o,yr):yr,n===yr)return e}return n},groupBy:function(t,e){return _e(this,t,e)},has:function(t){return this.get(t,yr)!==yr},hasIn:function(t){return this.getIn(t,yr)!==yr},isSubset:function(t){return t="function"==typeof t.includes?t:e(t),this.every(function(e){return t.includes(e)})},isSuperset:function(t){return t="function"==typeof t.isSubset?t:e(t),t.isSubset(this)},keyOf:function(t){return this.findKey(function(e){return X(e,t)})},keySeq:function(){return this.toSeq().map(Ge).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(t){return this.toKeyedSeq().reverse().keyOf(t)},max:function(t){return Se(this,t)},maxBy:function(t,e){return Se(this,e,t)},min:function(t){return Se(this,t?tr(t):nr)},minBy:function(t,e){return Se(this,e?tr(e):nr,t)},rest:function(){return this.slice(1)},skip:function(t){return this.slice(Math.max(0,t))},skipLast:function(t){return be(this,this.toSeq().reverse().skip(t).reverse())},skipWhile:function(t,e){return be(this,le(this,t,e,!0))},skipUntil:function(t,e){return this.skipWhile($e(t),e)},sortBy:function(t,e){return be(this,we(this,e,t))},take:function(t){return this.slice(0,Math.max(0,t))},takeLast:function(t){return be(this,this.toSeq().reverse().take(t).reverse());
},takeWhile:function(t,e){return be(this,ve(this,t,e))},takeUntil:function(t,e){return this.takeWhile($e(t),e)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=ir(this))}});var sn=e.prototype;sn[ar]=!0,sn[br]=sn.values,sn.__toJS=sn.toArray,sn.__toStringMapper=er,sn.inspect=sn.toSource=function(){return""+this},sn.chain=sn.flatMap,sn.contains=sn.includes,Fe(r,{flip:function(){return be(this,se(this))},mapEntries:function(t,e){var r=this,n=0;return be(this,this.toSeq().map(function(i,o){return t.call(e,[o,i],n++,r)}).fromEntrySeq())},mapKeys:function(t,e){var r=this;return be(this,this.toSeq().flip().map(function(n,i){return t.call(e,n,i,r)}).flip())}});var an=r.prototype;an[hr]=!0,an[br]=sn.entries,an.__toJS=sn.toObject,an.__toStringMapper=function(t,e){return JSON.stringify(e)+": "+er(t)},Fe(n,{toKeyedSeq:function(){return new ne(this,!1)},filter:function(t,e){return be(this,fe(this,t,e,!1))},findIndex:function(t,e){var r=this.findEntry(t,e);return r?r[0]:-1},indexOf:function(t){var e=this.keyOf(t);return void 0===e?-1:e},lastIndexOf:function(t){var e=this.lastKeyOf(t);return void 0===e?-1:e},reverse:function(){return be(this,he(this,!1))},slice:function(t,e){return be(this,pe(this,t,e,!1))},splice:function(t,e){var r=arguments.length;if(e=Math.max(0|e,0),0===r||2===r&&!e)return this;t=m(t,0>t?this.count():this.size);var n=this.slice(0,t);return be(this,1===r?n:n.concat(p(arguments,2),this.slice(t+e)))},findLastIndex:function(t,e){var r=this.findLastEntry(t,e);return r?r[0]:-1},first:function(){return this.get(0)},flatten:function(t){return be(this,de(this,t,!1))},get:function(t,e){return t=l(this,t),0>t||this.size===1/0||void 0!==this.size&&t>this.size?e:this.find(function(e,r){return r===t},void 0,e)},has:function(t){return t=l(this,t),t>=0&&(void 0!==this.size?this.size===1/0||this.size>t:-1!==this.indexOf(t))},interpose:function(t){return be(this,ge(this,t))},interleave:function(){var t=[this].concat(p(arguments)),e=Ie(this.toSeq(),k.of,t),r=e.flatten(!0);return e.size&&(r.size=e.size*t.length),
be(this,r)},keySeq:function(){return $(0,this.size)},last:function(){return this.get(-1)},skipWhile:function(t,e){return be(this,le(this,t,e,!1))},zip:function(){var t=[this].concat(p(arguments));return be(this,Ie(this,rr,t))},zipWith:function(t){var e=p(arguments);return e[0]=this,be(this,Ie(this,t,e))}}),n.prototype[fr]=!0,n.prototype[cr]=!0,Fe(i,{get:function(t,e){return this.has(t)?t:e},includes:function(t){return this.has(t)},keySeq:function(){return this.valueSeq()}}),i.prototype.has=sn.includes,i.prototype.contains=i.prototype.includes,Fe(x,r.prototype),Fe(k,n.prototype),Fe(A,i.prototype),Fe(et,r.prototype),Fe(rt,n.prototype),Fe(nt,i.prototype);var hn={Iterable:e,Seq:O,Collection:tt,Map:ct,OrderedMap:Zt,List:Bt,Stack:Ve,Set:Le,OrderedSet:Je,Record:Ae,Range:$,Repeat:G,is:X,fromJS:H};return hn});
+30 -11
View File
@@ -3,20 +3,39 @@
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname; var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
var specURL = currentPath + '?format=openapi'; var specURL = currentPath + '?format=openapi';
var redoc = document.createElement("redoc"); var redoc = document.createElement("redoc");
redoc.setAttribute("spec-url", specURL);
var redocSettings = JSON.parse(document.getElementById('redoc-settings').innerHTML); var redocSettings = JSON.parse(document.getElementById('redoc-settings').innerHTML);
if (redocSettings.lazyRendering) { if (redocSettings.url) {
redoc.setAttribute("lazy-rendering", ''); specURL = redocSettings.url;
} }
if (redocSettings.pathInMiddle) { delete redocSettings.url;
redoc.setAttribute("path-in-middle-panel", ''); if (redocSettings.fetchSchemaWithQuery) {
var query = new URLSearchParams(window.location.search || '').entries();
var url = specURL.split('?');
var usp = new URLSearchParams(url[1] || '');
for (var it = query.next(); !it.done; it = query.next()) {
usp.set(it.value[0], it.value[1]);
}
url[1] = usp.toString();
specURL = url[1] ? url.join('?') : url[0];
} }
if (redocSettings.hideHostname) { delete redocSettings.fetchSchemaWithQuery;
redoc.setAttribute("hide-hostname", '');
redoc.setAttribute("spec-url", specURL);
function camelToKebab(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
} }
redoc.setAttribute("expand-responses", redocSettings.expandResponses);
document.body.appendChild(redoc); for (var p in redocSettings) {
if (redocSettings.hasOwnProperty(p)) {
if (redocSettings[p] !== null && redocSettings[p] !== undefined && redocSettings[p] !== false) {
redoc.setAttribute(camelToKebab(p), redocSettings[p].toString());
}
}
}
document.body.replaceChild(redoc, document.getElementById('redoc-placeholder'));
function hideEmptyVersion() { function hideEmptyVersion() {
// 'span.api-info-version' is for redoc 1.x, 'div.api-info span' is for redoc 2-alpha // 'span.api-info-version' is for redoc 1.x, 'div.api-info span' is for redoc 2-alpha
@@ -29,8 +48,8 @@ function hideEmptyVersion() {
var versionString = apiVersion.innerText; var versionString = apiVersion.innerText;
if (versionString) { if (versionString) {
// trim spaces and surrounding () // trim spaces and surrounding ()
versionString = versionString.replace(/ /g,''); versionString = versionString.replace(/ /g, '');
versionString = versionString.replace(/(^\()|(\)$)/g,''); versionString = versionString.replace(/(^\()|(\)$)/g, '');
} }
if (!versionString) { if (!versionString) {
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

File diff suppressed because one or more lines are too long
-4
View File
@@ -19,10 +19,6 @@ body.swagger-body {
background: #fafafa; background: #fafafa;
} }
#django-session-auth {
margin-right: 8px;
}
.hidden { .hidden {
display: none; display: none;
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 445 B

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+348 -53
View File
@@ -1,22 +1,52 @@
"use strict"; "use strict";
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname; var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
var specURL = currentPath + '?format=openapi'; var defaultSpecUrl = currentPath + '?format=openapi';
// load the saved authorization state from localStorage; ImmutableJS is used for consistency with swagger-ui state
var savedAuth = Immutable.fromJS({});
// global SwaggerUI config object; can be changed directly or by hooking initSwaggerUiConfig
var swaggerUiConfig = {
url: defaultSpecUrl,
dom_id: '#swagger-ui',
displayRequestDuration: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
filter: true,
requestInterceptor: function (request) {
var headers = request.headers || {};
var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
if (csrftoken) {
headers["X-CSRFToken"] = csrftoken.value;
}
return request;
}
};
function patchSwaggerUi() { function patchSwaggerUi() {
var authWrapper = document.querySelector('.auth-wrapper');
var authorizeButton = document.querySelector('.auth-wrapper .authorize');
var djangoSessionAuth = document.querySelector('#django-session-auth');
if (document.querySelector('.auth-wrapper #django-session-auth')) { if (document.querySelector('.auth-wrapper #django-session-auth')) {
console.log("WARNING: session auth already patched; skipping patchSwaggerUi()");
return; return;
} }
var authWrapper = document.querySelector('.auth-wrapper');
var authorizeButton = document.querySelector('.auth-wrapper .authorize');
var djangoSessionAuth = document.querySelector('#django-session-auth');
if (!djangoSessionAuth) {
console.log("WARNING: session auth disabled");
return;
}
djangoSessionAuth = djangoSessionAuth.cloneNode(true);
authWrapper.insertBefore(djangoSessionAuth, authorizeButton); authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
djangoSessionAuth.classList.remove("hidden"); djangoSessionAuth.classList.remove("hidden");
var divider = document.createElement("div");
divider.classList.add("divider");
authWrapper.insertBefore(divider, authorizeButton);
} }
function initSwaggerUi() { function initSwaggerUi() {
@@ -24,59 +54,324 @@ function initSwaggerUi() {
console.log("WARNING: skipping initSwaggerUi() because window.ui is already defined"); console.log("WARNING: skipping initSwaggerUi() because window.ui is already defined");
return; return;
} }
var swaggerConfig = { if (document.querySelector('.auth-wrapper .authorize')) {
url: specURL, patchSwaggerUi();
dom_id: '#swagger-ui', }
displayOperationId: true, else {
displayRequestDuration: true, insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
presets: [ }
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
filter: true,
requestInterceptor: function (request) {
var headers = request.headers || {};
var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
if (csrftoken) {
headers["X-CSRFToken"] = csrftoken.value;
}
return request;
}
};
var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML); var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML);
if (!('oauth2RedirectUrl' in swaggerSettings)) {
var oauth2RedirectUrl = document.getElementById('oauth2-redirect-url'); var oauth2RedirectUrl = document.getElementById('oauth2-redirect-url');
if (oauth2RedirectUrl) { if (oauth2RedirectUrl) {
swaggerSettings['oauth2RedirectUrl'] = oauth2RedirectUrl.href; if (!('oauth2RedirectUrl' in swaggerSettings)) {
oauth2RedirectUrl.parentNode.removeChild(oauth2RedirectUrl); if (oauth2RedirectUrl) {
swaggerSettings['oauth2RedirectUrl'] = oauth2RedirectUrl.href;
}
} }
oauth2RedirectUrl.parentNode.removeChild(oauth2RedirectUrl);
} }
console.log(swaggerSettings); console.log('swaggerSettings', swaggerSettings);
for (var p in swaggerSettings) {
if (swaggerSettings.hasOwnProperty(p)) {
swaggerConfig[p] = swaggerSettings[p];
}
}
window.ui = SwaggerUIBundle(swaggerConfig);
var oauth2Config = JSON.parse(document.getElementById('oauth2-config').innerHTML); var oauth2Config = JSON.parse(document.getElementById('oauth2-config').innerHTML);
console.log(oauth2Config); console.log('oauth2Config', oauth2Config);
initSwaggerUiConfig(swaggerSettings, oauth2Config);
window.ui = SwaggerUIBundle(swaggerUiConfig);
window.ui.initOAuth(oauth2Config); window.ui.initOAuth(oauth2Config);
} }
window.onload = function () { /**
initSwaggerUi(); * Initialize the global swaggerUiConfig with any given additional settings.
}; * @param swaggerSettings SWAGGER_SETTINGS from Django settings
* @param oauth2Settings OAUTH2_CONFIG from Django settings
*/
function initSwaggerUiConfig(swaggerSettings, oauth2Settings) {
var persistAuth = swaggerSettings.persistAuth;
var refetchWithAuth = swaggerSettings.refetchWithAuth;
var refetchOnLogout = swaggerSettings.refetchOnLogout;
var fetchSchemaWithQuery = swaggerSettings.fetchSchemaWithQuery;
delete swaggerSettings['persistAuth'];
delete swaggerSettings['refetchWithAuth'];
delete swaggerSettings['refetchOnLogout'];
delete swaggerSettings['fetchSchemaWithQuery'];
if (document.querySelector('.auth-wrapper .authorize')) { for (var p in swaggerSettings) {
patchSwaggerUi(); if (swaggerSettings.hasOwnProperty(p)) {
swaggerUiConfig[p] = swaggerSettings[p];
}
}
var specURL = swaggerUiConfig.url;
if (fetchSchemaWithQuery) {
// only add query params from document for the first spec request
// this ensures we otherwise honor the spec selector box which might be manually modified
var query = new URLSearchParams(window.location.search || '').entries();
for (var it = query.next(); !it.done; it = query.next()) {
specURL = setQueryParam(specURL, it.value[0], it.value[1]);
}
}
if (persistAuth) {
try {
savedAuth = Immutable.fromJS(JSON.parse(localStorage.getItem("drf-yasg-auth")) || {});
} catch (e) {
localStorage.removeItem("drf-yasg-auth");
}
}
if (refetchWithAuth) {
specURL = applyAuth(savedAuth, specURL) || specURL;
}
swaggerUiConfig.url = specURL;
if (persistAuth || refetchWithAuth) {
var hookedAuth = false;
var oldOnComplete = swaggerUiConfig.onComplete;
swaggerUiConfig.onComplete = function () {
if (persistAuth) {
preauthorizeAll(savedAuth, window.ui);
}
if (!hookedAuth) {
hookAuthActions(window.ui, persistAuth, refetchWithAuth, refetchOnLogout);
hookedAuth = true;
}
if (oldOnComplete) {
oldOnComplete();
}
};
var specRequestsInFlight = {};
var oldRequestInterceptor = swaggerUiConfig.requestInterceptor;
swaggerUiConfig.requestInterceptor = function (request) {
var headers = request.headers || {};
if (request.loadSpec) {
var newUrl = request.url;
if (refetchWithAuth) {
newUrl = applyAuth(savedAuth, newUrl, headers) || newUrl;
}
if (newUrl !== request.url) {
request.url = newUrl;
if (window.ui) {
// this visually updates the spec url before the request is done, i.e. while loading
window.ui.specActions.updateUrl(request.url);
} else {
// setTimeout is needed here because the request interceptor can be called *during*
// window.ui initialization (by the SwaggerUIBundle constructor)
setTimeout(function () {
window.ui.specActions.updateUrl(request.url);
});
}
// need to manually remember requests for spec urls because
// responseInterceptor has no reference to the request...
var absUrl = new URL(request.url, currentPath);
specRequestsInFlight[absUrl.href] = request.url;
}
}
if (oldRequestInterceptor) {
request = oldRequestInterceptor(request);
}
return request;
};
var oldResponseInterceptor = swaggerUiConfig.responseInterceptor;
swaggerUiConfig.responseInterceptor = function (response) {
var absUrl = new URL(response.url, currentPath);
console.log("response", response);
if (absUrl.href in specRequestsInFlight) {
var setToUrl = specRequestsInFlight[absUrl.href];
delete specRequestsInFlight[absUrl.href];
if (response.ok) {
// need setTimeout here because swagger-ui insists to call updateUrl
// with the initial request url after the response...
setTimeout(function () {
var currentUrl = new URL(window.ui.specSelectors.url(), currentPath);
if (currentUrl.href !== absUrl.href) {
window.ui.specActions.updateUrl(setToUrl);
}
});
}
}
if (oldResponseInterceptor) {
response = oldResponseInterceptor(response);
}
return response;
}
}
} }
else {
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi); function _usp(url, fn) {
url = url.split('?');
var usp = new URLSearchParams(url[1] || '');
fn(usp);
url[1] = usp.toString();
return url[1] ? url.join('?') : url[0];
} }
function setQueryParam(url, key, value) {
return _usp(url, function (usp) {
usp.set(key, value);
});
}
function removeQueryParam(url, key) {
return _usp(url, function (usp) {
usp.delete(key);
})
}
/**
* Call sui.preauthorize### for all authorizations in authorization.
* @param authorization authorization object {key => authScheme} saved from authActions.authorize
* @param sui SwaggerUI or SwaggerUIBundle instance
*/
function preauthorizeAll(authorization, sui) {
authorization.valueSeq().forEach(function (authScheme) {
var schemeName = authScheme.get("name"), schemeType = authScheme.getIn(["schema", "type"]);
if (schemeType === "basic" && schemeName) {
var username = authScheme.getIn(["value", "username"]);
var password = authScheme.getIn(["value", "password"]);
if (username && password) {
sui.preauthorizeBasic(schemeName, username, password);
}
} else if (schemeType === "apiKey" && schemeName) {
var key = authScheme.get("value");
if (key) {
sui.preauthorizeApiKey(schemeName, key);
}
} else {
// TODO: OAuth2
}
});
}
/**
* Manually apply auth headers from the given auth object.
* @param {object} authorization authorization object {key => authScheme} saved from authActions.authorize
* @param {string} requestUrl the request url
* @param {object} requestHeaders target headers, modified in place by the function
* @return string new request url
*/
function applyAuth(authorization, requestUrl, requestHeaders) {
authorization.valueSeq().forEach(function (authScheme) {
requestHeaders = requestHeaders || {};
var schemeName = authScheme.get("name"), schemeType = authScheme.getIn(["schema", "type"]);
if (schemeType === "basic" && schemeName) {
var username = authScheme.getIn(["value", "username"]);
var password = authScheme.getIn(["value", "password"]);
if (username && password) {
requestHeaders["Authorization"] = "Basic " + btoa(username + ":" + password);
}
} else if (schemeType === "apiKey" && schemeName) {
var _in = authScheme.getIn(["schema", "in"]), paramName = authScheme.getIn(["schema", "name"]);
var key = authScheme.get("value");
if (key && paramName) {
if (_in === "header") {
requestHeaders[paramName] = key;
}
if (_in === "query") {
if (requestUrl) {
requestUrl = setQueryParam(requestUrl, paramName, key);
}
else {
console.warn("WARNING: cannot apply apiKey query parameter via interceptor");
}
}
}
} else {
// TODO: OAuth2
}
});
return requestUrl;
}
/**
* Remove the given authorization scheme from the url.
* @param {object} authorization authorization object {key => authScheme} containing schemes to deauthorize
* @param {string} requestUrl request url
* @return string new request url
*/
function deauthUrl(authorization, requestUrl) {
authorization.valueSeq().forEach(function (authScheme) {
var schemeType = authScheme.getIn(["schema", "type"]);
if (schemeType === "apiKey") {
var _in = authScheme.getIn(["schema", "in"]), paramName = authScheme.getIn(["schema", "name"]);
if (_in === "query" && requestUrl && paramName) {
requestUrl = removeQueryParam(requestUrl, paramName);
}
} else {
// TODO: OAuth2?
}
});
return requestUrl;
}
/**
* Hook the authorize and logout actions of SwaggerUI.
* The hooks are used to persist authorization data and trigger schema refetch.
* @param sui SwaggerUI or SwaggerUIBundle instance
* @param {boolean} persistAuth true to save auth to local storage
* @param {boolean} refetchWithAuth true to trigger schema fetch on login
* @param {boolean} refetchOnLogout true to trigger schema fetch on logout
*/
function hookAuthActions(sui, persistAuth, refetchWithAuth, refetchOnLogout) {
if (!persistAuth && !refetchWithAuth) {
// nothing to do
return;
}
var originalAuthorize = sui.authActions.authorize;
sui.authActions.authorize = function (authorization) {
originalAuthorize(authorization);
// authorization is map of scheme name to scheme object
// need to use ImmutableJS because schema is already an ImmutableJS object
var newAuths = Immutable.fromJS(authorization);
savedAuth = savedAuth.merge(newAuths);
if (refetchWithAuth) {
var url = sui.specSelectors.url();
url = applyAuth(savedAuth, url) || url;
sui.specActions.updateUrl(url);
sui.specActions.download();
sui.authActions.showDefinitions(); // hide authorize dialog
}
if (persistAuth) {
localStorage.setItem("drf-yasg-auth", JSON.stringify(savedAuth.toJSON()));
}
};
var originalLogout = sui.authActions.logout;
sui.authActions.logout = function (authorization) {
// stash logged out methods for use with deauthUrl
var loggedOut = savedAuth.filter(function (val, key) {
return authorization.indexOf(key) !== -1;
}).mapEntries(function (entry) {
return [entry[0], entry[1].set("value", null)]
});
// remove logged out methods from savedAuth
savedAuth = savedAuth.filter(function (val, key) {
return authorization.indexOf(key) === -1;
});
if (refetchWithAuth) {
var url = sui.specSelectors.url();
url = deauthUrl(loggedOut, url) || url;
sui.specActions.updateUrl(url);
sui.specActions.download(url);
sui.authActions.showDefinitions(); // hide authorize dialog
}
if (persistAuth) {
localStorage.setItem("drf-yasg-auth", JSON.stringify(savedAuth.toJSON()));
}
originalLogout(authorization);
};
}
window.addEventListener('load', initSwaggerUi);
File diff suppressed because one or more lines are too long
@@ -0,0 +1,18 @@
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
</head>
<body>
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script>
<script src="{% static 'drf-yasg/redoc-old/redoc.min.js' %}"></script>
</body>
</html>
+35 -4
View File
@@ -2,17 +2,48 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>{{ title }}</title>
<meta charset="utf-8"/> <meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{{ title }}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/> {% block extra_head %}
{# -- Add any extra HTML heads tags here - except scripts and styles -- #}
{% endblock %}
{% block favicon %}
{# -- Maybe replace the favicon -- #}
<link rel="icon" type="image/png" href="{% static 'drf-yasg/redoc/redoc-logo.png' %}"/>
{% endblock %}
{% block main_styles %}
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
{% endblock %}
{% block extra_styles %}
{# -- Add any additional CSS scripts here -- #}
{% endblock %}
</head> </head>
<body> <body>
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
{% block extra_body %}
{# -- Add any header/body markup here (rendered BEFORE the swagger-ui/redoc element) -- #}
{% endblock %}
<div id="redoc-placeholder"></div>
{% block footer %}
{# -- Add any footer markup here (rendered AFTER the swagger-ui/redoc element) -- #}
{% endblock %}
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
{% block main_scripts %}
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script> <script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script> <script src="{% static 'drf-yasg/url-polyfill.min.js' %}"></script>
<script src="{% static 'drf-yasg/redoc-init.js' %}"></script>
<script src="{% static 'drf-yasg/redoc/redoc.min.js' %}"></script> <script src="{% static 'drf-yasg/redoc/redoc.min.js' %}"></script>
{% endblock %}
{% block extra_scripts %}
{# -- Add any additional scripts here -- #}
{% endblock %}
</body> </body>
</html> </html>
+68 -75
View File
@@ -1,98 +1,91 @@
<!-- HTML for static distribution bundle build -->
{% load static %} {% load static %}
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="utf-8"/>
<title>{{ title }}</title> <title>{% block title %}{{ title }}{% endblock %}</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700"> {% block extra_head %}
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/> {# -- Add any extra HTML heads tags here - except scripts and styles -- #}
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/swagger-ui-dist/swagger-ui.css' %}"> {% endblock %}
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-32x32.png' %}" sizes="32x32"/>
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-16x16.png' %}" sizes="16x16"/>
{% block favicon %}
{# -- Maybe replace the favicon -- #}
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-32x32.png' %}"/>
{% endblock %}
{% block main_styles %}
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/swagger-ui-dist/swagger-ui.css' %}">
{% endblock %}
{% block extra_styles %}
{# -- Add any additional CSS scripts here -- #}
{% endblock %}
</head> </head>
<body class="swagger-body"> <body class="swagger-body">
<svg class="swagger-defs" xmlns="http://www.w3.org/2000/svg"> {% block extra_body %}
<defs> {# -- Add any header/body markup here (rendered BEFORE the swagger-ui/redoc element) -- #}
<symbol viewBox="0 0 20 20" id="unlocked"> {% endblock %}
<path
d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="locked">
<path
d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="close">
<path
d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow">
<path
d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow-down">
<path
d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"></path>
</symbol>
<symbol viewBox="0 0 24 24" id="jump-to">
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"></path>
</symbol>
<symbol viewBox="0 0 24 24" id="expand">
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"></path>
</symbol>
</defs>
</svg>
<div id="swagger-ui"></div> <div id="swagger-ui"></div>
<div id="spec-error" class="hidden alert alert-danger"></div>
{% block footer %}
{# -- Add any footer markup here (rendered AFTER the swagger-ui/redoc element) -- #}
{% endblock %}
<script id="swagger-settings" type="application/json">{{ swagger_settings | safe }}</script> <script id="swagger-settings" type="application/json">{{ swagger_settings | safe }}</script>
<script id="oauth2-config" type="application/json">{{ oauth2_config | safe }}</script> <script id="oauth2-config" type="application/json">{{ oauth2_config | safe }}</script>
<script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-bundle.js' %}"></script> {% block main_scripts %}
<script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-standalone-preset.js' %}"></script> <script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-bundle.js' %}"></script>
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script> <script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-standalone-preset.js' %}"></script>
<script src="{% static 'drf-yasg/swagger-ui-init.js' %}"></script> <script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
<script src="{% static 'drf-yasg/immutable.min.js' %}"></script>
<script src="{% static 'drf-yasg/url-polyfill.min.js' %}"></script>
<script src="{% static 'drf-yasg/swagger-ui-init.js' %}"></script>
{% endblock %}
{% block extra_scripts %}
{# -- Add any additional scripts here -- #}
{% endblock %}
<a id="oauth2-redirect-url" href="{% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}" class="hidden"></a> <a id="oauth2-redirect-url" href="{% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}" class="hidden"></a>
<div id="django-session-auth" class="hidden"> {% if USE_SESSION_AUTH %}
{% if USE_SESSION_AUTH %} <div id="django-session-auth" class="hidden">
{% csrf_token %} {% block session_auth_button %}
{% if request.user.is_authenticated %} {% csrf_token %}
<div class="hello">
<span class="django-session">Django</span> <span class="label label-primary">{{ request.user }}</span>
</div>
{% endif %}
{% if request.user.is_authenticated %} {% block user_context_message %}
<div class='btn authorize'> {% if request.user.is_authenticated %}
<a id="auth" class="header__btn" href="{{ LOGOUT_URL }}?next={{ request.path }}" data-sw-translate> <div class="hello">
Django Logout <span class="django-session">Django</span> <span
</a> class="label label-primary">{{ request.user }}</span>
</div> </div>
{% else %} {% endif %}
<div class='btn authorize'> {% endblock %}
<a id="auth" class="header__btn" href="{{ LOGIN_URL }}?next={{ request.path }}" data-sw-translate>
Django Login {% if request.user.is_authenticated %}
</a> <div class='btn authorize'>
</div> <a id="auth" class="header__btn" href="{{ LOGOUT_URL }}?next={{ request.path }}" data-sw-translate>
{% endif %} {% block django_logout_message %}
{% endif %} Django Logout
</div> {% endblock %}
</a>
</div>
{% else %}
<div class='btn authorize'>
<a id="auth" class="header__btn" href="{{ LOGIN_URL }}?next={{ request.path }}" data-sw-translate>
{% block django_login_message %}
Django Login
{% endblock %}
</a>
</div>
{% endif %}
{% endblock %}
</div>
{% endif %}
</body> </body>
</html> </html>
+119 -19
View File
@@ -8,8 +8,11 @@ from rest_framework import serializers, status
from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.request import is_form_media_type from rest_framework.request import is_form_media_type
from rest_framework.settings import api_settings as rest_framework_settings from rest_framework.settings import api_settings as rest_framework_settings
from rest_framework.utils import encoders, json
from rest_framework.views import APIView from rest_framework.views import APIView
from .app_settings import swagger_settings
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -24,9 +27,9 @@ class unset(object):
def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_body=None, query_serializer=None, 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, manual_parameters=None, operation_id=None, operation_description=None, operation_summary=None,
responses=None, field_inspectors=None, filter_inspectors=None, paginator_inspectors=None, security=None, deprecated=None, responses=None, field_inspectors=None, filter_inspectors=None,
**extra_overrides): paginator_inspectors=None, **extra_overrides):
"""Decorate a view method to customize the :class:`.Operation` object generated from it. """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 `method` and `methods` are mutually exclusive and must only be present when decorating a view method that accepts
@@ -47,7 +50,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
the `manual_parameters` argument. the `manual_parameters` argument.
If a ``Serializer`` class or instance is given, it will be automatically converted into a :class:`.Schema` If a ``Serializer`` class or instance is given, it will be automatically converted into a :class:`.Schema`
used as a ``body`` :class:`.Parameter`, or into a list of ``form`` :class:`.Parameter`\ s, as appropriate. used as a ``body`` :class:`.Parameter`, or into a list of ``form`` :class:`.Parameter`\\ s, as appropriate.
:param .Serializer query_serializer: if you use a ``Serializer`` to parse query parameters, you can pass it here :param .Serializer query_serializer: if you use a ``Serializer`` to parse query parameters, you can pass it here
and have :class:`.Parameter` objects be generated automatically from it. and have :class:`.Parameter` objects be generated automatically from it.
@@ -60,16 +63,18 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
:param list[.Parameter] manual_parameters: a list of manual parameters to override the automatically generated ones :param list[.Parameter] manual_parameters: a list of manual parameters to override the automatically generated ones
:class:`.Parameter`\ s are identified by their (``name``, ``in``) combination, and any parameters given :class:`.Parameter`\\ s are identified by their (``name``, ``in``) combination, and any parameters given
here will fully override automatically generated parameters if they collide. here will fully override automatically generated parameters if they collide.
It is an error to supply ``form`` parameters when the request does not consume form-data. It is an error to supply ``form`` parameters when the request does not consume form-data.
:param str operation_id: operation ID override; the operation ID must be unique accross the whole API :param str operation_id: operation ID override; the operation ID must be unique accross the whole API
:param str operation_description: operation description override :param str operation_description: operation description override
:param str operation_summary: operation summary string
:param list[dict] security: security requirements override; used to specify which authetication mechanism :param list[dict] security: security requirements override; used to specify which authetication mechanism
is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
authentication schemes), and ``None`` will inherit the top-level secuirty requirements authentication schemes), and ``None`` will inherit the top-level secuirty requirements
:param bool deprecated: deprecation status for operation
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses :param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
keyed on response status code. If no success (``2xx``) response is given, one will automatically be 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 generated from the request body and http method. If any ``2xx`` response is given the automatic response is
@@ -102,6 +107,8 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
'query_serializer': query_serializer, 'query_serializer': query_serializer,
'manual_parameters': manual_parameters, 'manual_parameters': manual_parameters,
'operation_id': operation_id, 'operation_id': operation_id,
'operation_summary': operation_summary,
'deprecated': deprecated,
'operation_description': operation_description, 'operation_description': operation_description,
'security': security, 'security': security,
'responses': responses, 'responses': responses,
@@ -115,21 +122,24 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
data.update(extra_overrides) data.update(extra_overrides)
if not data: # pragma: no cover if not data: # pragma: no cover
# no overrides to set, no use in doing more work # no overrides to set, no use in doing more work
return return view_method
# 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', []) 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 # if the method is actually a function based view (@api_view), it will have a 'cls' attribute
view_cls = getattr(view_method, 'cls', None) 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', {}) existing_data = getattr(view_method, '_swagger_auto_schema', {})
_methods = methods _methods = methods
if methods or method: if methods or method:
assert available_methods or http_method_names, "`method` or `methods` can only be specified " \ assert available_http_methods, "`method` or `methods` can only be specified on @action or @api_view views"
"on @action or @api_view views"
assert bool(methods) != bool(method), "specify either method or methods" assert bool(methods) != bool(method), "specify either method or methods"
assert not isinstance(methods, str), "`methods` expects to receive a list of methods;" \ assert not isinstance(methods, str), "`methods` expects to receive a list of methods;" \
" use `method` for a single argument" " use `method` for a single argument"
@@ -137,20 +147,20 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
_methods = [method.lower()] _methods = [method.lower()]
else: else:
_methods = [mth.lower() for mth in methods] _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" 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 # 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, \ assert _methods, \
"on multi-method api_view, action, detail_route or list_route, you must specify " \ "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" "swagger_auto_schema on a per-method basis using one of the `method` or `methods` arguments"
else: else:
# for a single-method view we assume that single method as the decorator target # 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), \ assert not any(hasattr(getattr(view_cls, mth, None), '_swagger_auto_schema') for mth in _methods), \
"swagger_auto_schema applied twice to method" "swagger_auto_schema applied twice to method"
@@ -170,6 +180,23 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
return decorator 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): 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). """Check if the given path/method appears to represent a list view (as opposed to a detail/instance view).
@@ -227,10 +254,26 @@ def param_list_to_odict(parameters):
return result return result
def merge_params(parameters, overrides):
"""Merge `overrides` into `parameters`. This is the same as appending `overrides` to `parameters`, but any element
of `parameters` whose ``(name, in_)`` tuple collides with an element in `overrides` is replaced by it.
Raises an ``AssertionError`` if either list contains duplicate parameters.
:param list[.Parameter] parameters: initial parameters
:param list[.Parameter] overrides: overriding parameters
:return: merged list
:rtype: list[.Parameter]
"""
parameters = param_list_to_odict(parameters)
parameters.update(param_list_to_odict(overrides))
return list(parameters.values())
def filter_none(obj): def filter_none(obj):
"""Remove ``None`` values from tuples, lists or dictionaries. Return other objects as-is. """Remove ``None`` values from tuples, lists or dictionaries. Return other objects as-is.
:param obj: :param obj: the object
:return: collection with ``None`` values removed :return: collection with ``None`` values removed
""" """
if obj is None: if obj is None:
@@ -251,6 +294,7 @@ def force_serializer_instance(serializer):
:param serializer: serializer class or instance :param serializer: serializer class or instance
:return: serializer instance :return: serializer instance
:rtype: serializers.BaseSerializer
""" """
if inspect.isclass(serializer): if inspect.isclass(serializer):
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__ assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
@@ -261,6 +305,26 @@ def force_serializer_instance(serializer):
return 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): def get_consumes(parser_classes):
"""Extract ``consumes`` MIME types from a list of parser classes. """Extract ``consumes`` MIME types from a list of parser classes.
@@ -284,7 +348,8 @@ def get_produces(renderer_classes):
:rtype: list[str] :rtype: list[str]
""" """
media_types = [renderer.media_type for renderer in renderer_classes or []] 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 return media_types
@@ -313,7 +378,7 @@ def get_serializer_ref_name(serializer):
if hasattr(serializer_meta, 'ref_name'): if hasattr(serializer_meta, 'ref_name'):
ref_name = serializer_meta.ref_name ref_name = serializer_meta.ref_name
elif serializer_name == 'NestedSerializer' and isinstance(serializer, serializers.ModelSerializer): 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 ref_name = None
else: else:
ref_name = serializer_name ref_name = serializer_name
@@ -334,3 +399,38 @@ def force_real_str(s, encoding='utf-8', strings_only=False, errors='strict'):
s = '' + s s = '' + s
return 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 and 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 = serializers.empty
return default
+17 -6
View File
@@ -11,12 +11,16 @@ from rest_framework.settings import api_settings
from rest_framework.views import APIView from rest_framework.views import APIView
from .app_settings import swagger_settings from .app_settings import swagger_settings
from .renderers import OpenAPIRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer from .renderers import (
OpenAPIRenderer, ReDocOldRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer,
_SpecRenderer
)
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer) SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
UI_RENDERERS = { UI_RENDERERS = {
'swagger': (SwaggerUIRenderer, ReDocRenderer), 'swagger': (SwaggerUIRenderer, ReDocRenderer),
'redoc': (ReDocRenderer, SwaggerUIRenderer), 'redoc': (ReDocRenderer, SwaggerUIRenderer),
'redoc-old': (ReDocOldRenderer, ReDocRenderer, SwaggerUIRenderer),
} }
@@ -45,9 +49,7 @@ def deferred_never_cache(view_func):
def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None, def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None,
generator_class=swagger_settings.DEFAULT_GENERATOR_CLASS, generator_class=None, authentication_classes=None, permission_classes=None):
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
"""Create a SchemaView class with default renderers and generators. """Create a SchemaView class with default renderers and generators.
:param .Info info: information about the API; if omitted, defaults to :ref:`DEFAULT_INFO <default-swagger-settings>` :param .Info info: information about the API; if omitted, defaults to :ref:`DEFAULT_INFO <default-swagger-settings>`
@@ -63,9 +65,13 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
:rtype: type[.SchemaView] :rtype: type[.SchemaView]
""" """
_public = public _public = public
_generator_class = generator_class _generator_class = generator_class or swagger_settings.DEFAULT_GENERATOR_CLASS
_auth_classes = authentication_classes _auth_classes = authentication_classes
if _auth_classes is None:
_auth_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
_perm_classes = permission_classes _perm_classes = permission_classes
if _perm_classes is None:
_perm_classes = api_settings.DEFAULT_PERMISSION_CLASSES
info = info or swagger_settings.DEFAULT_INFO info = info or swagger_settings.DEFAULT_INFO
validators = validators or [] validators = validators or []
_spec_renderers = tuple(renderer.with_validators(validators) for renderer in SPEC_RENDERERS) _spec_renderers = tuple(renderer.with_validators(validators) for renderer in SPEC_RENDERERS)
@@ -80,7 +86,12 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
renderer_classes = _spec_renderers renderer_classes = _spec_renderers
def get(self, request, version='', format=None): def get(self, request, version='', format=None):
generator = self.generator_class(info, request.version or version or '', url, patterns, urlconf) version = request.version or version or ''
if isinstance(request.accepted_renderer, _SpecRenderer):
generator = self.generator_class(info, version, url, patterns, urlconf)
else:
generator = self.generator_class(info, version, url, patterns=[])
schema = generator.get_schema(request, self.public) schema = generator.get_schema(request, self.public)
if schema is None: if schema is None:
raise exceptions.PermissionDenied() # pragma: no cover raise exceptions.PermissionDenied() # pragma: no cover
+6 -1
View File
@@ -33,7 +33,12 @@ class ArticleSerializer(serializers.ModelSerializer):
class ImageUploadSerializer(serializers.Serializer): class ImageUploadSerializer(serializers.Serializer):
what_am_i_doing = serializers.RegexField(regex=r"^69$", help_text="test", default="69") what_am_i_doing = serializers.RegexField(
regex=r"^69$",
help_text="test",
default="69",
allow_null=True
)
image_styles = serializers.ListSerializer( image_styles = serializers.ListSerializer(
child=serializers.ChoiceField(choices=['wide', 'tall', 'thumb', 'social']), child=serializers.ChoiceField(choices=['wide', 'tall', 'thumb', 'social']),
help_text="Parameter with Items" help_text="Parameter with Items"
+4 -2
View File
@@ -15,7 +15,7 @@ from articles.models import Article
from drf_yasg import openapi from drf_yasg import openapi
from drf_yasg.app_settings import swagger_settings from drf_yasg.app_settings import swagger_settings
from drf_yasg.inspectors import CoreAPICompatInspector, FieldInspector, NotHandled, SwaggerAutoSchema from drf_yasg.inspectors import CoreAPICompatInspector, FieldInspector, NotHandled, SwaggerAutoSchema
from drf_yasg.utils import swagger_auto_schema from drf_yasg.utils import no_body, swagger_auto_schema
class DjangoFilterDescriptionInspector(CoreAPICompatInspector): class DjangoFilterDescriptionInspector(CoreAPICompatInspector):
@@ -133,11 +133,13 @@ class ArticleViewSet(viewsets.ModelViewSet):
""" """
pass pass
@swagger_auto_schema(request_body=no_body, operation_id='no_body_test')
def update(self, request, *args, **kwargs): def update(self, request, *args, **kwargs):
"""update method docstring""" """update method docstring"""
return super(ArticleViewSet, self).update(request, *args, **kwargs) return super(ArticleViewSet, self).update(request, *args, **kwargs)
@swagger_auto_schema(operation_description="partial_update description override", responses={404: 'slug not found'}) @swagger_auto_schema(operation_description="partial_update description override", responses={404: 'slug not found'},
operation_summary='partial_update summary', deprecated=True)
def partial_update(self, request, *args, **kwargs): def partial_update(self, request, *args, **kwargs):
"""partial_update method docstring""" """partial_update method docstring"""
return super(ArticleViewSet, self).partial_update(request, *args, **kwargs) return super(ArticleViewSet, self).partial_update(request, *args, **kwargs)
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',
),
]
+2 -2
View File
@@ -3,8 +3,8 @@ from django.utils.safestring import mark_safe
class Identity(models.Model): class Identity(models.Model):
firstName = models.CharField(max_length=30, null=True) first_name = models.CharField(max_length=30, null=True)
lastName = models.CharField(max_length=30, null=True, help_text=mark_safe("<strong>Here's some HTML!</strong>")) last_name = models.CharField(max_length=30, null=True, help_text=mark_safe("<strong>Here's some HTML!</strong>"))
class Person(models.Model): class Person(models.Model):
+22
View File
@@ -23,12 +23,34 @@ class ExampleProjectSerializer(serializers.Serializer):
ref_name = 'Project' 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): class SnippetSerializer(serializers.Serializer):
"""SnippetSerializer classdoc """SnippetSerializer classdoc
create: docstring for create from serializer classdoc create: docstring for create from serializer classdoc
""" """
id = serializers.IntegerField(read_only=True, help_text="id serializer help text") id = serializers.IntegerField(read_only=True, help_text="id serializer help text")
created = UnixTimestampField(read_only=True)
owner = serializers.PrimaryKeyRelatedField( owner = serializers.PrimaryKeyRelatedField(
queryset=get_user_model().objects.all(), queryset=get_user_model().objects.all(),
default=serializers.CurrentUserDefault(), default=serializers.CurrentUserDefault(),
+4
View File
@@ -46,6 +46,10 @@ class SnippetList(generics.ListCreateAPIView):
), ),
) )
def delete(self, *args, **kwargs): def delete(self, *args, **kwargs):
"""summary from docstring
description body is here, summary is not included
"""
pass pass
+19 -2
View File
@@ -1,6 +1,8 @@
import os import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from django.urls import reverse_lazy
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ALLOWED_HOSTS = [ ALLOWED_HOSTS = [
@@ -47,7 +49,7 @@ ROOT_URLCONF = 'testproj.urls'
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], 'DIRS': [os.path.join(BASE_DIR, 'testproj', 'templates')],
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
@@ -91,8 +93,11 @@ REST_FRAMEWORK = {
# drf-yasg # drf-yasg
SWAGGER_SETTINGS = { SWAGGER_SETTINGS = {
'LOGIN_URL': '/admin/login', 'LOGIN_URL': reverse_lazy('admin:login'),
'LOGOUT_URL': '/admin/logout', 'LOGOUT_URL': '/admin/logout',
'PERSIST_AUTH': True,
'REFETCH_SCHEMA_WITH_AUTH': True,
'REFETCH_SCHEMA_ON_LOGOUT': True,
'DEFAULT_INFO': 'testproj.urls.swagger_info', 'DEFAULT_INFO': 'testproj.urls.swagger_info',
@@ -104,10 +109,19 @@ SWAGGER_SETTINGS = {
'type': 'apiKey', 'type': 'apiKey',
'name': 'Authorization', 'name': 'Authorization',
'in': 'header' 'in': 'header'
},
'Query': {
'type': 'apiKey',
'name': 'auth',
'in': 'query'
} }
} }
} }
REDOC_SETTINGS = {
'SPEC_URL': ('schema-json', {'format': '.json'}),
}
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/ # https://docs.djangoproject.com/en/1.11/topics/i18n/
@@ -126,6 +140,9 @@ USE_TZ = True
STATIC_URL = '/static/' STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'testproj', 'static'),
]
# Testing # Testing
View File
+1
View File
@@ -51,6 +51,7 @@ urlpatterns = [
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'), url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
url(r'^redoc-old/$', SchemaView.with_ui('redoc-old', cache_timeout=0), name='schema-redoc-old'),
url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'), url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'),
url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'), url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'),
@@ -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
+64 -1
View File
@@ -1,8 +1,19 @@
from django.contrib.auth.models import User from django.contrib.auth.models import User
from rest_framework import serializers from rest_framework import serializers
from drf_yasg.utils import swagger_serializer_method
from snippets.models import Snippet 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): class UserSerializerrr(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
@@ -10,12 +21,64 @@ class UserSerializerrr(serializers.ModelSerializer):
last_connected_ip = serializers.IPAddressField(help_text="i'm out of ideas", protocol='ipv4', read_only=True) 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) 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: class Meta:
model = User model = User
fields = ('id', 'username', 'email', 'articles', 'snippets', 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): class UserListQuerySerializer(serializers.Serializer):
username = serializers.CharField(help_text="this field is generated from a query_serializer", required=False) username = serializers.CharField(help_text="this field is generated from a query_serializer", required=False)
is_staff = serializers.BooleanField(help_text="this one too!", required=False) is_staff = serializers.BooleanField(help_text="this one too!", required=False)
styles = serializers.MultipleChoiceField(help_text="and this one is fancy!", choices=('a', 'b', 'c', 'd'))
+2 -2
View File
@@ -6,7 +6,7 @@ from rest_framework.response import Response
from rest_framework.views import APIView from rest_framework.views import APIView
from drf_yasg import openapi from drf_yasg import openapi
from drf_yasg.utils import no_body, swagger_auto_schema from drf_yasg.utils import swagger_auto_schema
from users.serializers import UserListQuerySerializer, UserSerializerrr from users.serializers import UserListQuerySerializer, UserSerializerrr
@@ -36,7 +36,7 @@ class UserList(APIView):
serializer.save() serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED)
@swagger_auto_schema(request_body=no_body, operation_id="users_dummy", operation_description="dummy operation") @swagger_auto_schema(operation_id="users_dummy", operation_description="dummy operation")
def patch(self, request): def patch(self, request):
pass pass
+159 -12
View File
@@ -27,9 +27,14 @@ securityDefinitions:
in: header in: header
name: Authorization name: Authorization
type: apiKey type: apiKey
Query:
in: query
name: auth
type: apiKey
security: security:
- Basic: [] - Basic: []
- Bearer: [] - Bearer: []
- Query: []
paths: paths:
/articles/: /articles/:
get: get:
@@ -134,14 +139,9 @@ paths:
tags: tags:
- articles - articles
put: put:
operationId: articles_update operationId: no_body_test
description: update method docstring description: update method docstring
parameters: parameters: []
- name: data
in: body
required: true
schema:
$ref: '#/definitions/Article'
responses: responses:
'200': '200':
description: '' description: ''
@@ -151,6 +151,7 @@ paths:
- articles - articles
patch: patch:
operationId: articles_partial_update operationId: articles_partial_update
summary: partial_update summary
description: partial_update description override description: partial_update description override
parameters: parameters:
- name: data - name: data
@@ -167,6 +168,7 @@ paths:
description: slug not found description: slug not found
tags: tags:
- articles - articles
deprecated: true
delete: delete:
operationId: articles_delete operationId: articles_delete
description: destroy method docstring description: destroy method docstring
@@ -192,6 +194,8 @@ paths:
responses: responses:
'200': '200':
description: '' description: ''
schema:
$ref: '#/definitions/Article'
consumes: consumes:
- multipart/form-data - multipart/form-data
tags: tags:
@@ -208,6 +212,7 @@ paths:
pattern: ^69$ pattern: ^69$
default: '69' default: '69'
minLength: 1 minLength: 1
x-nullable: true
- name: image_styles - name: image_styles
in: formData in: formData
description: Parameter with Items description: Parameter with Items
@@ -228,6 +233,8 @@ paths:
responses: responses:
'201': '201':
description: '' description: ''
schema:
$ref: '#/definitions/ImageUpload'
consumes: consumes:
- multipart/form-data - multipart/form-data
tags: tags:
@@ -390,7 +397,8 @@ paths:
- snippets - snippets
delete: delete:
operationId: snippetsDeleteBulk operationId: snippetsDeleteBulk
description: SnippetList classdoc summary: summary from docstring
description: description body is here, summary is not included
parameters: parameters:
- name: data - name: data
in: body in: body
@@ -732,6 +740,19 @@ paths:
description: this one too! description: this one too!
required: false required: false
type: boolean type: boolean
- name: styles
in: query
description: and this one is fancy!
required: true
type: array
items:
type: string
enum:
- a
- b
- c
- d
collectionFormat: multi
responses: responses:
'200': '200':
description: '' description: ''
@@ -883,6 +904,7 @@ definitions:
- 3 - 3
- 7 - 7
- 8 - 8
x-nullable: true
group: group:
type: string type: string
format: uuid format: uuid
@@ -890,6 +912,33 @@ definitions:
type: string type: string
format: uuid format: uuid
readOnly: true readOnly: true
ImageUpload:
required:
- image_styles
type: object
properties:
what_am_i_doing:
description: test
type: string
pattern: ^69$
default: '69'
minLength: 1
x-nullable: true
image_styles:
description: Parameter with Items
type: array
items:
type: string
enum:
- wide
- tall
- thumb
- social
upload:
description: image serializer help_text
type: string
readOnly: true
format: uri
Identity: Identity:
title: Identity title: Identity
type: object type: object
@@ -898,17 +947,19 @@ definitions:
title: ID title: ID
type: integer type: integer
readOnly: true readOnly: true
firstName: first_name:
title: FirstName title: First name
type: string type: string
maxLength: 30 maxLength: 30
minLength: 1 minLength: 1
lastName: x-nullable: true
title: LastName last_name:
title: Last name
description: <strong>Here's some HTML!</strong> description: <strong>Here's some HTML!</strong>
type: string type: string
maxLength: 30 maxLength: 30
minLength: 1 minLength: 1
x-nullable: true
Person: Person:
required: required:
- identity - identity
@@ -947,6 +998,12 @@ definitions:
description: id serializer help text description: id serializer help text
type: integer type: integer
readOnly: true readOnly: true
created:
title: Client date time suu
type: string
format: integer
readOnly: true
description: Date time in unix timestamp format
owner: owner:
title: Owner title: Owner
description: The ID of the user that created this snippet; if none is provided, description: The ID of the user that created this snippet; if none is provided,
@@ -1115,6 +1172,7 @@ definitions:
- fan - fan
- fancy - fancy
- felix - felix
- fennel
- fish - fish
- flatline - flatline
- forth - forth
@@ -1140,6 +1198,7 @@ definitions:
- haskell - haskell
- haxeml - haxeml
- hexdump - hexdump
- hlsl
- hsail - hsail
- html - html
- html+cheetah - html+cheetah
@@ -1406,6 +1465,7 @@ definitions:
- xml+php - xml+php
- xml+smarty - xml+smarty
- xml+velocity - xml+velocity
- xorg.conf
- xquery - xquery
- xslt - xslt
- xtend - xtend
@@ -1454,6 +1514,7 @@ definitions:
type: array type: array
items: items:
type: integer type: integer
x-nullable: true
exampleProjects: exampleProjects:
type: array type: array
items: items:
@@ -1518,6 +1579,7 @@ definitions:
parent_id: parent_id:
type: integer type: integer
title: Parent id title: Parent id
x-nullable: true
TodoTree: TodoTree:
required: required:
- title - title
@@ -1582,11 +1644,76 @@ definitions:
todo: todo:
title: child title: child
todo: null 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
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: UserSerializerrr:
required: required:
- username - username
- articles - articles
- snippets - snippets
- hint_example
type: object type: object
properties: properties:
id: id:
@@ -1637,3 +1764,23 @@ definitions:
pattern: ^[-a-zA-Z0-9_]+$ pattern: ^[-a-zA-Z0-9_]+$
readOnly: true readOnly: true
uniqueItems: 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
-2
View File
@@ -1,5 +1,3 @@
from six import StringIO
import json import json
import os import os
import random import random
+2 -2
View File
@@ -25,8 +25,8 @@ def test_validator_url(swagger_settings, swagger):
swagger_settings['VALIDATOR_URL'] = None swagger_settings['VALIDATOR_URL'] = None
_check_swagger_setting(swagger, 'validatorUrl', None) _check_swagger_setting(swagger, 'validatorUrl', None)
swagger_settings['VALIDATOR_URL'] = 'not none' swagger_settings['VALIDATOR_URL'] = 'http://not.none/'
_check_swagger_setting(swagger, 'validatorUrl', 'not none') _check_swagger_setting(swagger, 'validatorUrl', 'http://not.none/')
with pytest.raises(KeyError): with pytest.raises(KeyError):
swagger_settings['VALIDATOR_URL'] = '' swagger_settings['VALIDATOR_URL'] = ''
+43
View File
@@ -147,3 +147,46 @@ def test_url_order():
# get_endpoints only includes one endpoint # get_endpoints only includes one endpoint
assert len(generator.get_endpoints(None)['/test/'][1]) == 1 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'
+14 -15
View File
@@ -1,28 +1,26 @@
[tox] [tox]
# https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django
envlist = envlist =
py27-django111-drf37, py{27,34,35,36}-django111-drf{37,38},
py{34,35,36}-django{111,20}-drf{37,38}, py{34,35,36,37}-django20-drf{37,38},
py36-django20-drfmaster, py{35,36,37}-django21-drf{37,38},
lint, docs djmaster, lint, docs
[travis:env]
DRF =
3.7: drf37
3.8: drf38
master: drfmaster
[testenv] [testenv]
deps = deps =
django111: Django>=1.11,<2.0 django111: Django>=1.11,<2.0
django20: Django>=2.0,<2.1 django20: Django>=2.0,<2.1
django21: Django>=2.1,<2.2
drf37: djangorestframework>=3.7.7,<3.8 drf37: djangorestframework>=3.7.7,<3.8
drf38: djangorestframework>=3.8.0,<3.9 drf38: djangorestframework>=3.8.0,<3.9
# test with the latest build of django-rest-framework to get early warning of compatibility issues # 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 # other dependencies
-rrequirements/setup.txt
-rrequirements/validation.txt -rrequirements/validation.txt
-rrequirements/test.txt -rrequirements/test.txt
@@ -38,6 +36,7 @@ commands =
[testenv:docs] [testenv:docs]
deps = deps =
-rrequirements/setup.txt
-rrequirements/docs.txt -rrequirements/docs.txt
commands = commands =
python setup.py check --restructuredtext --metadata --strict python setup.py check --restructuredtext --metadata --strict
@@ -46,21 +45,21 @@ commands =
[pytest] [pytest]
DJANGO_SETTINGS_MODULE = testproj.settings.local DJANGO_SETTINGS_MODULE = testproj.settings.local
python_paths = testproj python_paths = testproj
addopts = -n 3 --ignore=node_modules addopts = -n 2 --ignore=node_modules
[flake8] [flake8]
max-line-length = 120 max-line-length = 120
exclude = **/migrations/* exclude = **/migrations/*
ignore = F405 ignore = F405,W504
[isort] [isort]
skip = .eggs,.tox,docs,env,venv skip = .eggs,.tox,docs,env,venv,node_modules
skip_glob = **/migrations/* skip_glob = **/migrations/*
not_skip = __init__.py not_skip = __init__.py
atomic = true atomic = true
multi_line_output = 5 multi_line_output = 5
line_length = 120 line_length = 120
known_future_library = future,six known_future_library = six
known_standard_library = known_standard_library =
collections,copy,distutils,functools,inspect,io,json,logging,operator,os,pkg_resources,re,setuptools,sys, collections,copy,distutils,functools,inspect,io,json,logging,operator,os,pkg_resources,re,setuptools,sys,
types,warnings types,warnings
Regular → Executable
+4 -2
View File
@@ -3,8 +3,10 @@ set -ev
npm update npm update
cp node_modules/redoc/bundles/redoc.standalone.js src/drf_yasg/static/drf-yasg/redoc/redoc.min.js cp node_modules/redoc/bundles/redoc.standalone.js src/drf_yasg/static/drf-yasg/redoc/redoc.min.js
wget https://rebilly.github.io/ReDoc/releases/v1.x.x/redoc.min.js -O src/drf_yasg/static/drf-yasg/redoc-old/redoc.min.js
cp -r node_modules/swagger-ui-dist src/drf_yasg/static/drf-yasg/ cp -r node_modules/swagger-ui-dist src/drf_yasg/static/drf-yasg/
pushd src/drf_yasg/static/drf-yasg/swagger-ui-dist/ >/dev/null pushd src/drf_yasg/static/drf-yasg/swagger-ui-dist/ >/dev/null
rm -f package.json .npmignore README.md rm -f package.json .npmignore README.md favicon-16x16.png
rm -f index.html *.map rm -f swagger-ui.js index.html *.map
popd >/dev/null popd >/dev/null