Compare commits
133 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 904895ba3c | |||
| 79adfc19be | |||
| 2965e08e39 | |||
| f2e05ee4c0 | |||
| bbc70a7e3d | |||
| ca43a7de0c | |||
| cc43bdf5cb | |||
| db86981dc1 | |||
| b37ce3227a | |||
| 8fbab88bda | |||
| 58b979f4ea | |||
| d9b6fbc1b8 | |||
| 20370d912e | |||
| 178390a9a0 | |||
| 7982f62f38 | |||
| 9fa4765121 | |||
| 544d72db0a | |||
| 696ec3a94a | |||
| e0aec3ff45 | |||
| ee7b9a0734 | |||
| 0697c415ed | |||
| 4825ec70b1 | |||
| 54ad90415d | |||
| 1184ea8b46 | |||
| 6ac58b8cf7 | |||
| d627a1bc5d | |||
| 38e884b5ea | |||
| 2ef7cfbfe3 | |||
| 58adbb8f4c | |||
| 34c7fa2b0e | |||
| 6b2ce7d0f9 | |||
| 256a052564 | |||
| cc90bc1544 | |||
| ecee6f8177 | |||
| 408b31fc4f | |||
| a4a11ad1ab | |||
| aca0c4713e | |||
| 3077195396 | |||
| 94f6ca8c89 | |||
| ae5eeeb600 | |||
| 23ebe2ff3e | |||
| 713c669e28 | |||
| 2545ae9657 | |||
| f03d9d71e9 | |||
| a993cba7aa | |||
| bfd88cbdb4 | |||
| 123a05c82c | |||
| 7065429d47 | |||
| bd727fbe88 | |||
| 698a175a1b | |||
| 5b225423ae | |||
| 209201b9a5 | |||
| ca00ed35be | |||
| 4e7fa28744 | |||
| 979ec84630 | |||
| d2dc09cb3c | |||
| 36992072ca | |||
| aa90723703 | |||
| 301511bebc | |||
| c0f37f6ec1 | |||
| 5e684549a1 | |||
| 322971f3e7 | |||
| 6dd8ded05d | |||
| 7270154828 | |||
| 6f7d14fdb2 | |||
| 941ec8fdaf | |||
| 51ec07261d | |||
| a9cdf6d561 | |||
| a64ce95e3c | |||
| c9147a5746 | |||
| ccdf646c0e | |||
| 04252ebec3 | |||
| 848fb69009 | |||
| 309a6eb8cd | |||
| a7fbba4967 | |||
| 66785b1ee8 | |||
| fb240f6a5b | |||
| 2c459024d1 | |||
| b62161f762 | |||
| 9ad55bac99 | |||
| 3d3b7899e5 | |||
| 6ea8711a1f | |||
| ee46f59fb1 | |||
| 3f7ad62950 | |||
| b38d3e6805 | |||
| 058fd7096d | |||
| a32321d43a | |||
| f15e70b7db | |||
| 64c280e222 | |||
| d5073081d9 | |||
| 10c7e22940 | |||
| 6c497b32b4 | |||
| 73c60a8fda | |||
| 97082e8898 | |||
| 743396617e | |||
| 97cd1b63d9 | |||
| 71dee6eb45 | |||
| 7fa0cc0639 | |||
| e8c688f981 | |||
| c01a6ead26 | |||
| 05901e99aa | |||
| a211184478 | |||
| a3e81ef7f6 | |||
| a46b684fea | |||
| fc35d9043e | |||
| f18ff60ae7 | |||
| a82730d32b | |||
| e30af0287f | |||
| fc253665dd | |||
| 33199aec59 | |||
| 9d1150f1ab | |||
| bc4037f721 | |||
| 6c4dcb18bb | |||
| 4445137d55 | |||
| 57870d12a4 | |||
| 7a3fe8ec0c | |||
| 757d47e1c0 | |||
| 59a51ba4a7 | |||
| 55223e32e2 | |||
| 6a478e14d7 | |||
| 57d77cc48a | |||
| c225f66fb7 | |||
| 47de6f2f6f | |||
| 8dbf3fe984 | |||
| 1c3fba6e54 | |||
| c4379dc6a7 | |||
| 6b38a3b6c1 | |||
| 464a518ae5 | |||
| 15c67891c6 | |||
| 917ccd1f56 | |||
| fd099998ea | |||
| a6e24e20c3 | |||
| 6608e0050c |
+7
-1
@@ -1,6 +1,8 @@
|
||||
[run]
|
||||
source = drf_yasg
|
||||
branch = True
|
||||
parallel = true
|
||||
disable_warnings = module-not-measured
|
||||
|
||||
[report]
|
||||
# Regexes for lines to exclude from consideration
|
||||
@@ -18,7 +20,10 @@ exclude_lines =
|
||||
raise TypeError
|
||||
raise NotImplementedError
|
||||
warnings.warn
|
||||
logger.debug
|
||||
logger.info
|
||||
logger.warning
|
||||
logger.error
|
||||
return NotHandled
|
||||
|
||||
# Don't complain if non-runnable code isn't run:
|
||||
@@ -29,7 +34,8 @@ exclude_lines =
|
||||
raise SwaggerGenerationError
|
||||
|
||||
ignore_errors = True
|
||||
precision = 0
|
||||
precision = 2
|
||||
show_missing = True
|
||||
|
||||
[paths]
|
||||
source =
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
node_modules/
|
||||
testproj/db.sqlite3
|
||||
testproj/staticfiles
|
||||
.vscode/
|
||||
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
@@ -158,3 +159,5 @@ com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
\.pytest_cache/
|
||||
|
||||
Generated
+5
-3
@@ -4,18 +4,20 @@
|
||||
<facet type="django" name="Django">
|
||||
<configuration>
|
||||
<option name="rootFolder" value="$MODULE_DIR$/testproj" />
|
||||
<option name="settingsModule" value="testproj/settings.py" />
|
||||
<option name="settingsModule" value="testproj/settings/local.py" />
|
||||
<option name="manageScript" value="manage.py" />
|
||||
<option name="environment" value="<map/>" />
|
||||
<option name="doNotUseTestRunner" value="false" />
|
||||
<option name="trackFilePattern" value="migrations" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/testproj" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/docs/_build" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/venv" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Python 3.6 (drf-yasg)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
@@ -24,7 +26,7 @@
|
||||
<option name="TEMPLATE_CONFIGURATION" value="Django" />
|
||||
<option name="TEMPLATE_FOLDERS">
|
||||
<list>
|
||||
<option value="$MODULE_DIR$/drf_yasg/templates" />
|
||||
<option value="$MODULE_DIR$/src/drf_yasg/templates" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
|
||||
+2
-1
@@ -10,11 +10,12 @@
|
||||
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ourVersions">
|
||||
<value>
|
||||
<list size="4">
|
||||
<list size="5">
|
||||
<item index="0" class="java.lang.String" itemvalue="2.7" />
|
||||
<item index="1" class="java.lang.String" itemvalue="3.4" />
|
||||
<item index="2" class="java.lang.String" itemvalue="3.5" />
|
||||
<item index="3" class="java.lang.String" itemvalue="3.6" />
|
||||
<item index="4" class="java.lang.String" itemvalue="3.7" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
|
||||
Generated
+3
@@ -70,4 +70,7 @@
|
||||
</LinkMapSettings>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (drf-yasg)" project-jdk-type="Python SDK" />
|
||||
<component name="PythonCompatibilityInspectionAdvertiser">
|
||||
<option name="version" value="3" />
|
||||
</component>
|
||||
</project>
|
||||
+46
-35
@@ -1,56 +1,34 @@
|
||||
language: python
|
||||
cache: pip
|
||||
|
||||
python:
|
||||
- '2.7'
|
||||
- '3.4'
|
||||
- '3.5'
|
||||
- '3.6'
|
||||
- '3.7-dev'
|
||||
|
||||
env:
|
||||
- DRF=3.7
|
||||
|
||||
install:
|
||||
- pip install -r requirements/ci.txt
|
||||
|
||||
before_script:
|
||||
- coverage erase
|
||||
|
||||
script:
|
||||
- tox
|
||||
|
||||
after_success:
|
||||
- codecov
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- /^release\/.*$/
|
||||
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: always
|
||||
on_failure: always
|
||||
- DRF=3.8
|
||||
|
||||
jobs:
|
||||
fast_finish: true
|
||||
|
||||
include:
|
||||
- stage: test
|
||||
python: '2.7'
|
||||
env: DRF=3.7
|
||||
-
|
||||
python: '3.6'
|
||||
env: DRF=master
|
||||
-
|
||||
python: '3.5'
|
||||
env: TOXENV=docs
|
||||
-
|
||||
python: '2.7'
|
||||
env: TOXENV=flake8
|
||||
-
|
||||
python: '3.6'
|
||||
env: DRF=master
|
||||
env: TOXENV=lint
|
||||
|
||||
- stage: publish
|
||||
python: '3.6'
|
||||
script: skip
|
||||
env:
|
||||
env: PYPI_DEPLOY=true
|
||||
deploy: &pypi
|
||||
provider: pypi
|
||||
user: cvijdea
|
||||
@@ -58,14 +36,47 @@ jobs:
|
||||
secure: 54DvknusZ7uHlo9IJxgbNDVKYrwaScyuOZyAGZPb/PTUj8WroQZtp1bFOrAtzfcM4ctIIoLWVzmSwrxypmU4hNif2ZvJ8Vo2PnVh9G6wQ2fD2FN+kFBYczBNrzW5xhjJ53OiTYy/zzHgzxC/sp+hB4sibWl0v69PGU5v6oyBltOWZLXYpqMA6fINt62XDVwuNHVKAo1T/yoeJMQKeCKYAx8QOtve9/qcl5Td/OOM6z42hX5+q3N7RgkCFLl0KopwaPwBaL1Z3Bn+aUhiIUdrRrdigY329QtNXoa/VRBNvUSAwbvecShmgl3c9HigL2ZWmtmHaXda6YCdqmbVfSHSEDsn4AwhZ3A9WblbRtuBwP79YKiE+4BLmgLlGGA4IrAKr3woe+078q/bGqBzmeDd+jt72hhibzD5B96zo4tSNksSxSJGwMYH988fBN/ppynrzRvO0sR/THwpb0r42era8tRd3ZVBefloVas/nQZZs4+zMYoO0fbaLDXdkfaxsF5/X6WkwTYjbI3tdapUT6lYXwi1eKUM1ZGsfKpuq0lFa3qxevYBKveWStQwGyJz1KhVUHbo3OrA3U6q9yoqpzhcZBhzGAPSgumi+EkBUj69cymlYkmqXVBn4VnWsdeFefNYE6Kvh/HJEDPDaWSNgfVLN9xWVqJqM7QiWA351W9dRZA=
|
||||
on:
|
||||
tags: true
|
||||
distributions: sdist
|
||||
distributions: "sdist bdist_wheel"
|
||||
|
||||
allow_failures:
|
||||
- env: TOXENV=flake8
|
||||
- env: TOXENV=lint
|
||||
- env: DRF=master
|
||||
- python: '3.7-dev'
|
||||
|
||||
fast_finish: true
|
||||
|
||||
install:
|
||||
- pip install -r requirements/ci.txt
|
||||
|
||||
before_script:
|
||||
- coverage erase
|
||||
- |
|
||||
[[ -z "$TOXENV" && -z "$PYPI_DEPLOY" ]] && REPORT_COVERAGE="yes" || REPORT_COVERAGE="no";
|
||||
echo "Reporting coverage: ${REPORT_COVERAGE}"
|
||||
- |
|
||||
[[ -z "$TOXENV" && ! -z "$DRF" && "$DRF" != "master" ]] && USE_DETOX="yes" || USE_DETOX="no";
|
||||
echo "Using detox: ${USE_DETOX}"
|
||||
|
||||
script:
|
||||
- 'if [[ "$USE_DETOX" == "yes" ]]; then detox; else tox; fi'
|
||||
|
||||
after_success:
|
||||
- coverage combine
|
||||
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then coverage report; fi'
|
||||
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then codecov; fi'
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- /^release\/.*$/
|
||||
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
|
||||
|
||||
stages:
|
||||
- test
|
||||
- name: publish
|
||||
if: tag IS present
|
||||
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: always
|
||||
on_failure: always
|
||||
|
||||
+23
-1
@@ -36,7 +36,7 @@ You want to contribute some code? Great! Here are a few steps to get you started
|
||||
$ virtualenv venv
|
||||
$ source venv/bin/activate
|
||||
(venv) $ pip install -e .[validation]
|
||||
(venv) $ pip install -rrequirements/dev.txt -rrequirements/test.txt "Django>=1.11.7"
|
||||
(venv) $ pip install -r requirements/dev.txt
|
||||
|
||||
#. **Make your changes and check them against the test project**
|
||||
|
||||
@@ -95,3 +95,25 @@ You want to contribute some code? Great! Here are a few steps to get you started
|
||||
#. **Your code must pass all the required travis jobs before it is merged**
|
||||
|
||||
As of now, this consists of running on Python 2.7, 3.4, 3.5 and 3.6, and building the docs succesfully.
|
||||
|
||||
******************
|
||||
Maintainer's notes
|
||||
******************
|
||||
|
||||
Release checklist
|
||||
=================
|
||||
|
||||
* update ``docs/changelog.rst`` with changes since the last tagged version
|
||||
* commit & tag the release - ``git tag x.x.x -m "Release version x.x.x"``
|
||||
* push using ``git push --follow-tags``
|
||||
* verify that `Travis`_ has built the tag and succesfully published the release to `PyPI`_
|
||||
* publish release notes `on GitHub`_
|
||||
* start the `ReadTheDocs build`_ if it has not already started
|
||||
* deploy the live demo `on Heroku`_
|
||||
|
||||
|
||||
.. _Travis: https://travis-ci.org/axnsan12/drf-yasg/builds
|
||||
.. _PyPI: https://pypi.org/project/drf-yasg/
|
||||
.. _on GitHub: https://github.com/axnsan12/drf-yasg/releases
|
||||
.. _ReadTheDocs build: https://readthedocs.org/projects/drf-yasg/builds/
|
||||
.. _on Heroku: https://dashboard.heroku.com/pipelines/412d1cae-6a95-4f5e-810b-94869133f36a
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ License
|
||||
BSD 3-Clause License
|
||||
********************
|
||||
|
||||
Copyright (c) 2017, Cristian V. <cristi@cvjd.me> |br|\ All rights reserved.
|
||||
Copyright (c) 2018, Cristian V. <cristi@cvjd.me> |br|\ All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
release: python testproj/manage.py migrate && python testproj/manage.py shell -c "import createsuperuser"
|
||||
web: gunicorn --chdir testproj testproj.wsgi --log-file -
|
||||
+43
-91
@@ -11,30 +11,39 @@ Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framewor
|
||||
|
||||
Compatible with
|
||||
|
||||
- **Django Rest Framework**: 3.7
|
||||
- **Django**: 1.11, 2.0
|
||||
- **Django Rest Framework**: 3.7.7, 3.8.x
|
||||
- **Django**: 1.11.x, 2.0.x
|
||||
- **Python**: 2.7, 3.4, 3.5, 3.6
|
||||
|
||||
**Source**: https://github.com/axnsan12/drf-yasg/
|
||||
Resources:
|
||||
|
||||
**Documentation**: https://drf-yasg.readthedocs.io/en/latest/
|
||||
* **Source**: https://github.com/axnsan12/drf-yasg/
|
||||
* **Documentation**: https://drf-yasg.readthedocs.io/
|
||||
* **Changelog**: https://drf-yasg.readthedocs.io/en/stable/changelog.html
|
||||
* **Live demo**: https://drf-yasg-demo.herokuapp.com/
|
||||
|
||||
.. image:: https://www.herokucdn.com/deploy/button.svg
|
||||
:target: https://heroku.com/deploy?template=https://github.com/axnsan12/drf-yasg
|
||||
:alt: heroku deploy button
|
||||
|
||||
********
|
||||
Features
|
||||
********
|
||||
|
||||
- full support for nested Serializers and Schemas
|
||||
- response schemas and descriptions
|
||||
- model definitions compatible with codegen tools
|
||||
- customization hooks at all points in the spec generation process
|
||||
- JSON and YAML format for spec
|
||||
- bundles latest version of
|
||||
`swagger-ui <https://github.com/swagger-api/swagger-ui>`_ and
|
||||
`redoc <https://github.com/Rebilly/ReDoc>`_ for viewing the generated documentation
|
||||
- schema view is cacheable out of the box
|
||||
- generated Swagger schema can be automatically validated by
|
||||
`swagger-spec-validator <https://github.com/Yelp/swagger_spec_validator>`_ or
|
||||
`flex <https://github.com/pipermerriam/flex>`_
|
||||
- full support for nested Serializers and Schemas
|
||||
- response schemas and descriptions
|
||||
- model definitions compatible with codegen tools
|
||||
- customization hooks at all points in the spec generation process
|
||||
- JSON and YAML format for spec
|
||||
- bundles latest version of
|
||||
`swagger-ui <https://github.com/swagger-api/swagger-ui>`_ and
|
||||
`redoc <https://github.com/Rebilly/ReDoc>`_ for viewing the generated documentation
|
||||
- schema view is cacheable out of the box
|
||||
- generated Swagger schema can be automatically validated by
|
||||
`swagger-spec-validator <https://github.com/Yelp/swagger_spec_validator>`_ or
|
||||
`flex <https://github.com/pipermerriam/flex>`_
|
||||
- supports Django REST Framework API versioning with ``URLPathVersioning`` and ``NamespaceVersioning``; other DRF
|
||||
or custom versioning schemes are not currently supported
|
||||
|
||||
.. figure:: https://raw.githubusercontent.com/axnsan12/drf-yasg/1.0.2/screenshots/redoc-nested-response.png
|
||||
:width: 100%
|
||||
@@ -119,15 +128,15 @@ In ``urls.py``:
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
),
|
||||
validators=['ssv', 'flex'],
|
||||
validators=['flex', 'ssv'],
|
||||
public=True,
|
||||
permission_classes=(permissions.AllowAny,),
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^swagger(?P<format>.json|.yaml)$', schema_view.without_ui(cache_timeout=None), name='schema-json'),
|
||||
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'),
|
||||
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=None), name='schema-redoc'),
|
||||
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
|
||||
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
|
||||
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
|
||||
...
|
||||
]
|
||||
|
||||
@@ -145,12 +154,13 @@ This exposes 4 cached, validated and publicly available endpoints:
|
||||
a. ``get_schema_view`` parameters
|
||||
---------------------------------
|
||||
|
||||
- ``info`` - Required. Swagger API Info object
|
||||
- ``info`` - Swagger API Info object; if omitted, defaults to ``DEFAULT_INFO``
|
||||
- ``url`` - API base url; if left blank will be deduced from the location the view is served at
|
||||
- ``patterns`` - passed to SchemaGenerator
|
||||
- ``urlconf`` - passed to SchemaGenerator
|
||||
- ``public`` - if False, includes only endpoints the current user has access to
|
||||
- ``validators`` - a list of validator names to apply on the generated schema; allowed values are ``flex``, ``ssv``
|
||||
- ``generator_class`` - schema generator class to use; should be a subclass of ``OpenAPISchemaGenerator``
|
||||
- ``authentication_classes`` - authentication classes for the schema view itself
|
||||
- ``permission_classes`` - permission classes for the schema view itself
|
||||
|
||||
@@ -166,81 +176,17 @@ b. ``SchemaView`` options
|
||||
but with optional caching
|
||||
- you can, of course, call :python:`as_view` as usual
|
||||
|
||||
All of the first 3 methods take two optional arguments,
|
||||
``cache_timeout`` and ``cache_kwargs``; if present, these are passed on
|
||||
to Django’s :python:`cached_page` decorator in order to enable caching on the
|
||||
resulting view. See `3. Caching`_.
|
||||
All of the first 3 methods take two optional arguments, ``cache_timeout`` and ``cache_kwargs``; if present,
|
||||
these are passed on to Django’s :python:`cached_page` decorator in order to enable caching on the resulting view.
|
||||
See `3. Caching`_.
|
||||
|
||||
----------------------------------------------
|
||||
c. ``SWAGGER_SETTINGS`` and ``REDOC_SETTINGS``
|
||||
----------------------------------------------
|
||||
|
||||
Additionally, you can include some more settings in your ``settings.py`` file.
|
||||
The possible settings and their default values are as follows:
|
||||
See https://drf-yasg.readthedocs.io/en/stable/settings.html for details.
|
||||
|
||||
.. code:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
# default inspector classes, see advanced documentation
|
||||
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.inspectors.SwaggerAutoSchema',
|
||||
'DEFAULT_FIELD_INSPECTORS': [
|
||||
'drf_yasg.inspectors.CamelCaseJSONFilter',
|
||||
'drf_yasg.inspectors.ReferencingSerializerInspector',
|
||||
'drf_yasg.inspectors.RelatedFieldInspector',
|
||||
'drf_yasg.inspectors.ChoiceFieldInspector',
|
||||
'drf_yasg.inspectors.FileFieldInspector',
|
||||
'drf_yasg.inspectors.DictFieldInspector',
|
||||
'drf_yasg.inspectors.SimpleFieldInspector',
|
||||
'drf_yasg.inspectors.StringDefaultFieldInspector',
|
||||
],
|
||||
'DEFAULT_FILTER_INSPECTORS': [
|
||||
'drf_yasg.inspectors.CoreAPICompatInspector',
|
||||
],
|
||||
'DEFAULT_PAGINATOR_INSPECTORS': [
|
||||
'drf_yasg.inspectors.DjangoRestResponsePagination',
|
||||
'drf_yasg.inspectors.CoreAPICompatInspector',
|
||||
],
|
||||
|
||||
# default api Info if none is otherwise given; should be an import string to an openapi.Info object
|
||||
'DEFAULT_INFO': None,
|
||||
# default API url if none is otherwise given
|
||||
'DEFAULT_API_URL': '',
|
||||
|
||||
'USE_SESSION_AUTH': True, # add Django Login and Django Logout buttons, CSRF token to swagger UI page
|
||||
'LOGIN_URL': getattr(django.conf.settings, 'LOGIN_URL', None), # URL for the login button
|
||||
'LOGOUT_URL': getattr(django.conf.settings, 'LOGOUT_URL', None), # URL for the logout button
|
||||
|
||||
# Swagger security definitions to include in the schema;
|
||||
# see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-definitions-object
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'basic': {
|
||||
'type': 'basic'
|
||||
}
|
||||
},
|
||||
|
||||
# url to an external Swagger validation service; defaults to 'http://online.swagger.io/validator/'
|
||||
# set to None to disable the schema validation badge in the UI
|
||||
'VALIDATOR_URL': '',
|
||||
|
||||
# swagger-ui configuration settings, see https://github.com/swagger-api/swagger-ui/blob/112bca906553a937ac67adc2e500bdeed96d067b/docs/usage/configuration.md#parameters
|
||||
'OPERATIONS_SORTER': None,
|
||||
'TAGS_SORTER': None,
|
||||
'DOC_EXPANSION': 'list',
|
||||
'DEEP_LINKING': False,
|
||||
'SHOW_EXTENSIONS': True,
|
||||
'DEFAULT_MODEL_RENDERING': 'model',
|
||||
'DEFAULT_MODEL_DEPTH': 3,
|
||||
}
|
||||
|
||||
.. code:: python
|
||||
|
||||
REDOC_SETTINGS = {
|
||||
# ReDoc UI configuration settings, see https://github.com/Rebilly/ReDoc#redoc-tag-attributes
|
||||
'LAZY_RENDERING': True,
|
||||
'HIDE_HOSTNAME': False,
|
||||
'EXPAND_RESPONSES': 'all',
|
||||
'PATH_IN_MIDDLE': False,
|
||||
}
|
||||
|
||||
3. Caching
|
||||
==========
|
||||
@@ -260,7 +206,7 @@ caching the schema view in-memory, with some sane defaults:
|
||||
|
||||
Given the numerous methods to manually customzie the generated schema, it makes sense to validate the result to ensure
|
||||
it still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swagger
|
||||
libraries, and can be activated by passing :python:`validators=['ssv', 'flex']` to ``get_schema_view``; if the generated
|
||||
libraries, and can be activated by passing :python:`validators=['flex', 'ssv']` to ``get_schema_view``; if the generated
|
||||
schema is not valid, a :python:`SwaggerValidationError` is raised by the handling codec.
|
||||
|
||||
**Warning:** This internal validation can slow down your server.
|
||||
@@ -407,6 +353,12 @@ Integration with `djangorestframework-camel-case <https://github.com/vbabiy/djan
|
||||
provided out of the box - if you have ``djangorestframework-camel-case`` installed and your ``APIView`` uses
|
||||
``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer``, all property names will be converted to *camelCase* by default.
|
||||
|
||||
djangorestframework-recursive
|
||||
===============================
|
||||
|
||||
Integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_ is
|
||||
provided out of the box - if you have ``djangorestframework-recursive`` installed.
|
||||
|
||||
.. |travis| image:: https://img.shields.io/travis/axnsan12/drf-yasg/master.svg
|
||||
:target: https://travis-ci.org/axnsan12/drf-yasg
|
||||
:alt: Travis CI
|
||||
@@ -416,7 +368,7 @@ provided out of the box - if you have ``djangorestframework-camel-case`` install
|
||||
:alt: Codecov
|
||||
|
||||
.. |pypi-version| image:: https://img.shields.io/pypi/v/drf-yasg.svg
|
||||
:target: https://pypi.python.org/pypi/drf-yasg/
|
||||
:target: https://pypi.org/project/drf-yasg/
|
||||
:alt: PyPI
|
||||
|
||||
.. |rtd-badge| image:: https://img.shields.io/readthedocs/drf-yasg.svg
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "drf-yasg Demo app",
|
||||
"description": "A demonstrative app using https://github.com/axnsan12/drf-yasg",
|
||||
"repository": "https://github.com/axnsan12/drf-yasg",
|
||||
"logo": "https://swaggerhub.com/wp-content/uploads/2017/10/Swagger-Icon.svg",
|
||||
"keywords": [
|
||||
"django",
|
||||
"django-rest-framework",
|
||||
"swagger",
|
||||
"openapi"
|
||||
],
|
||||
"env": {
|
||||
"DJANGO_SETTINGS_MODULE": "testproj.settings.heroku",
|
||||
"DJANGO_SECRET_KEY": "m76=^#=z7xv5^(o%4dv9w7+1_c)y2m6)1ogjx%s@9$1^nupry="
|
||||
},
|
||||
"success_url": "/"
|
||||
}
|
||||
@@ -3,10 +3,300 @@ Changelog
|
||||
#########
|
||||
|
||||
|
||||
**********
|
||||
**1.9.2**
|
||||
**********
|
||||
|
||||
*Release date: Aug 03, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.17.6
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.32
|
||||
- **IMPROVED:** added ``--api-version`` argument to the ``generate_swagger`` management command (:pr:`170`)
|
||||
- **FIXED:** corrected various documentation typos (:pr:`160`, :pr:`162`, :issue:`171`, :pr:`172`)
|
||||
- **FIXED:** made ``generate_swagger`` work for projects without authentication (:pr:`161`)
|
||||
- **FIXED:** fixed ``SafeText`` interaction with YAML codec (:issue:`159`)
|
||||
|
||||
*********
|
||||
**1.9.1**
|
||||
*********
|
||||
|
||||
*Release date: Jun 30, 2018*
|
||||
|
||||
- **IMPROVED:** added a ``swagger_fake_view`` marker to more easily detect mock views in view methods;
|
||||
``getattr(self, 'swagger_fake_view', False)`` inside a view method like ``get_serializer_class`` will tell you if the
|
||||
view instnace is being used for swagger schema introspection (:issue:`154`)
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.17.1
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.25
|
||||
- **FIXED:** fixed wrong handling of duplicate urls in urlconf (:pr:`155`)
|
||||
- **FIXED:** fixed crash when passing ``None`` as a response override (:issue:`148`)
|
||||
|
||||
*********
|
||||
**1.9.0**
|
||||
*********
|
||||
|
||||
*Release date: Jun 16, 2018*
|
||||
|
||||
- **ADDED:** added ``DEFAULT_GENERATOR_CLASS`` setting and ``--generator-class`` argument to the ``generate_swagger``
|
||||
management command (:issue:`140`)
|
||||
- **FIXED:** fixed wrongly required ``'count'`` response field on ``CursorPagination`` (:issue:`141`)
|
||||
- **FIXED:** fixed some cases where ``swagger_extra_fields`` would not be handlded (:pr:`142`)
|
||||
- **FIXED:** fixed crash when encountering ``coreapi.Fields``\ s without a ``schema`` (:issue:`143`)
|
||||
|
||||
*********
|
||||
**1.8.0**
|
||||
*********
|
||||
|
||||
*Release date: Jun 01, 2018*
|
||||
|
||||
- **ADDED:** added a :ref:`swagger_schema_fields <swagger_schema_fields>` field on serializer ``Meta`` classes for
|
||||
customizing schema generation (:issue:`132`, :pr:`134`)
|
||||
- **FIXED:** error responses from schema views are now rendered with ``JSONRenderer`` instead of throwing
|
||||
confusing errors (:pr:`130`, :issue:`58`)
|
||||
- **FIXED:** ``readOnly`` schema fields will now no longer be marked as ``required`` (:pr:`133`)
|
||||
|
||||
*********
|
||||
**1.7.4**
|
||||
*********
|
||||
|
||||
*Release date: May 14, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.14.2
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.20
|
||||
- **FIXED:** ignore ``None`` return from ``get_operation`` to avoid empty ``Path`` objects in output
|
||||
- **FIXED:** request body is now allowed on ``DELETE`` endpoints (:issue:`118`)
|
||||
|
||||
*********
|
||||
**1.7.3**
|
||||
*********
|
||||
|
||||
*Release date: May 12, 2018*
|
||||
|
||||
- **FIXED:** views whose ``__init__`` methods throw exceptions will now be ignored during endpoint enumeration
|
||||
|
||||
*********
|
||||
**1.7.2**
|
||||
*********
|
||||
|
||||
*Release date: May 12, 2018*
|
||||
|
||||
- **FIXED:** fixed generation of default ``SECURITY_REQUIREMENTS`` to match documented behaviour
|
||||
- **FIXED:** ordering of ``SECURITY_REQUIREMENTS`` and ``SECURITY_DEFINITIONS`` is now stable
|
||||
|
||||
*********
|
||||
**1.7.1**
|
||||
*********
|
||||
|
||||
*Release date: May 05, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.14.1
|
||||
- **IMPROVED:** set ``swagger-ui`` ``showCommonExtensions`` to ``True`` by default and add
|
||||
``SHOW_COMMON_EXTENSIONS`` setting key
|
||||
- **IMPROVED:** set ``min_length=1`` when ``allow_blank=False`` (:pr:`112`, thanks to :ghuser:`elnappo`)
|
||||
- **FIXED:** made documentation ordering of ``SwaggerDict`` extra attributes stable
|
||||
|
||||
*********
|
||||
**1.7.0**
|
||||
*********
|
||||
|
||||
*Release date: Apr 27, 2018*
|
||||
|
||||
- **ADDED:** added integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_
|
||||
(:issue:`109`, :pr:`110`, thanks to :ghuser:`rsichny`)
|
||||
|
||||
*NOTE:* in order for this to work, you will have to add the new ``drf_yasg.inspectors.RecursiveFieldInspector`` to
|
||||
your ``DEFAULT_FIELD_INSPECTORS`` array if you changed it from the default value
|
||||
|
||||
- **FIXED:** ``SchemaRef`` now supports cyclical references via the ``ignore_unresolved`` argument
|
||||
|
||||
*********
|
||||
**1.6.2**
|
||||
*********
|
||||
|
||||
*Release date: Apr 25, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.13.6
|
||||
- **IMPROVED:** switched ``ReDoc`` to version 2.0.0-alpha.17 (was 1.21.2); fixes :issue:`107`
|
||||
- **FIXED:** made documentation ordering of parameters stable for urls with multiple parameters (:issue:`105`, :pr:`106`)
|
||||
- **FIXED:** fixed crash when using a model ``ChoiceField`` of unknown child type
|
||||
|
||||
*********
|
||||
**1.6.1**
|
||||
*********
|
||||
|
||||
*Release date: Apr 01, 2018*
|
||||
|
||||
- **ADDED:** added ``SUPPORTED_SUBMIT_METHODS`` ``swagger-ui`` setting
|
||||
|
||||
*********
|
||||
**1.6.0**
|
||||
*********
|
||||
|
||||
*Release date: Mar 24, 2018*
|
||||
|
||||
- **IMPROVED:** ``OAUTH2_REDIRECT_URL`` will now default to the built in ``oauth2-redirect.html`` file
|
||||
|
||||
*********
|
||||
**1.5.1**
|
||||
*********
|
||||
|
||||
*Release date: Mar 18, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.13.0
|
||||
- **FIXED:** fixed a crash caused by ``serializers.OneToOneRel`` (:pr:`81`, thanks to :ghuser:`ko-pp`)
|
||||
|
||||
*********
|
||||
**1.5.0**
|
||||
*********
|
||||
|
||||
*Release date: Mar 12, 2018*
|
||||
|
||||
- **IMPROVED:** ``serializers.HiddenField`` are now hidden (:issue:`78`, :pr:`79`, thanks to :ghuser:`therefromhere`)
|
||||
|
||||
*NOTE:* in order for this to work, you will have to add the new ``drf_yasg.inspectors.HiddenFieldInspector`` to your
|
||||
``DEFAULT_FIELD_INSPECTORS`` array if you changed it from the default value
|
||||
|
||||
- **IMPROVED:** type of model field is now detected for ``serializers.SlugRelatedField`` with ``read_only=True``
|
||||
(:issue:`82`, :pr:`83`, thanks to :ghuser:`therefromhere`)
|
||||
|
||||
*********
|
||||
**1.4.7**
|
||||
*********
|
||||
|
||||
*Release date: Mar 05, 2018*
|
||||
|
||||
- **FIXED:** prevent crashes caused by attempting to delete object attributes which do not exist in the first place
|
||||
(:issue:`76`)
|
||||
|
||||
*********
|
||||
**1.4.6**
|
||||
*********
|
||||
|
||||
*Release date: Mar 05, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.12.0
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 1.21.2
|
||||
|
||||
*********
|
||||
**1.4.5**
|
||||
*********
|
||||
|
||||
*Release date: Mar 05, 2018*
|
||||
|
||||
- **FIXED:** fixed an issue with modification of ``swagger_auto_schema`` arguments in-place during introspection, which
|
||||
would sometimes cause an incomplete Swagger document to be generated after the first pass (:issue:`74`, :pr:`75`)
|
||||
|
||||
*********
|
||||
**1.4.4**
|
||||
*********
|
||||
|
||||
*Release date: Feb 26, 2018*
|
||||
|
||||
- **IMPROVED:** ``type`` for ``ChoiceField`` generated by a ``ModelSerializer`` from a model field with ``choices=...``
|
||||
will now be set according to the associated model field (:issue:`69`)
|
||||
- **FIXED:** ``lookup_field`` and ``lookup_value_regex`` on the same ``ViewSet`` will no longer trigger an exception
|
||||
(:issue:`68`)
|
||||
|
||||
*********
|
||||
**1.4.3**
|
||||
*********
|
||||
|
||||
*Release date: Feb 22, 2018*
|
||||
|
||||
- **FIXED:** added a missing assignment that would cause the ``default`` argument to ``openapi.Parameter.__init__`` to
|
||||
be ignored
|
||||
|
||||
*********
|
||||
**1.4.2**
|
||||
*********
|
||||
|
||||
*Release date: Feb 22, 2018*
|
||||
|
||||
- **FIXED:** fixed a bug that causes a ``ModelViewSet`` generated from models with nested ``ForeignKey`` to output
|
||||
models named ``Nested`` into the ``definitions`` section (:issue:`59`, :pr:`65`)
|
||||
- **FIXED:** ``Response`` objects without a ``schema`` are now properly handled when passed through
|
||||
``swagger_auto_schema`` (:issue:`66`)
|
||||
|
||||
*********
|
||||
**1.4.1**
|
||||
*********
|
||||
|
||||
*Release date: Feb 21, 2018*
|
||||
|
||||
- **FIXED:** the ``coerce_to_string`` is now respected when setting the type, default value and min/max values of
|
||||
``DecimalField`` in the OpenAPI schema (:issue:`62`)
|
||||
- **FIXED:** error responses from web UI views are now rendered with ``TemplateHTMLRenderer`` instead of throwing
|
||||
confusing errors (:issue:`58`)
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.10.0
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 1.21.0
|
||||
|
||||
*********
|
||||
**1.4.0**
|
||||
*********
|
||||
|
||||
*Release date: Feb 04, 2018*
|
||||
|
||||
- **ADDED:** added settings for OAuth2 client configuration in ``swagger-ui`` (:issue:`53`)
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.9.3
|
||||
|
||||
*********
|
||||
**1.3.1**
|
||||
*********
|
||||
|
||||
*Release date: Jan 24, 2018*
|
||||
|
||||
- **FIXED:** fixed a bug that would sometimes cause endpoints to wrongly be output as form operations (:issue:`50`)
|
||||
- **IMPROVED:** added generation of ``produces`` based on renderer classes
|
||||
- **IMPROVED:** added generation of top-level ``consumes`` and ``produces`` based on
|
||||
``DEFAULT_PARSER_CLASSES`` and ``DEFAULT_RENDERER_CLASSES`` (:issue:`48`)
|
||||
|
||||
*********
|
||||
**1.3.0**
|
||||
*********
|
||||
|
||||
*Release date: Jan 23, 2018*
|
||||
|
||||
- **ADDED:** security requirements are now correctly set and can be customized; this should fix problems related
|
||||
to authentication in ``swagger-ui`` Try it out! (:issue:`50`, :pr:`54`)
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.9.2
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 1.20.0
|
||||
- **FIXED:** fixed an exception caused by a warning in get_path_from_regex (:pr:`49`, thanks to :ghuser:`blueyed`)
|
||||
|
||||
*********
|
||||
**1.2.2**
|
||||
*********
|
||||
|
||||
*Release date: Jan 12, 2018*
|
||||
|
||||
- **FIXED:** djangorestframework>=3.7.7 is now required because of breaking changes
|
||||
(:issue:`44`, :pr:`45`, thanks to :ghuser:`h-hirokawa`)
|
||||
|
||||
*********
|
||||
**1.2.1**
|
||||
*********
|
||||
|
||||
*Release date: Jan 12, 2018*
|
||||
|
||||
- Fixed deployment issues
|
||||
|
||||
*********
|
||||
**1.2.0**
|
||||
*********
|
||||
|
||||
*Release date: Jan 12, 2018 (missing from PyPI due to deployment issues)*
|
||||
|
||||
- **ADDED:** ``basePath`` is now generated by taking into account the ``SCRIPT_NAME`` variable and the
|
||||
longest common prefix of API urls (:issue:`37`, :pr:`42`)
|
||||
- **IMPROVED:** removed inline scripts and styles from bundled HTML templates to increase CSP compatibility
|
||||
- **IMPROVED:** improved validation errors and added more assertion sanity checks (:issue:`37`, :issue:`40`)
|
||||
- **IMPROVED:** improved handling of NamespaceVersioning by excluding endpoints of differing versions
|
||||
(i.e. when accesing the schema view for v1, v2 endpoints will not be included in swagger)
|
||||
|
||||
*********
|
||||
**1.1.3**
|
||||
*********
|
||||
|
||||
*Release date: Jan 02, 2018*
|
||||
|
||||
- **FIXED:** schema view cache will now always ``Vary`` on the ``Cookie`` and ``Authentication`` (the
|
||||
``Vary`` header was previously only added if ``public`` was set to ``True``) - this fixes issues related to Django
|
||||
authentication in ``swagger-ui`` and ``CurrentUserDefault`` values in the schema
|
||||
@@ -15,6 +305,8 @@ Changelog
|
||||
**1.1.2**
|
||||
*********
|
||||
|
||||
*Release date: Jan 01, 2018*
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.8.1
|
||||
- **IMPROVED:** removed some unneeded static files
|
||||
|
||||
@@ -22,6 +314,8 @@ Changelog
|
||||
**1.1.1**
|
||||
*********
|
||||
|
||||
*Release date: Dec 27, 2017*
|
||||
|
||||
- **ADDED:** :ref:`generate_swagger management command <management-command>`
|
||||
(:issue:`29`, :pr:`31`, thanks to :ghuser:`beaugunderson`)
|
||||
- **FIXED:** fixed improper generation of ``\Z`` regex tokens - will now be repalced by ``$``
|
||||
@@ -30,6 +324,8 @@ Changelog
|
||||
**1.1.0**
|
||||
*********
|
||||
|
||||
*Release date: Dec 27, 2017*
|
||||
|
||||
- **ADDED:** added support for APIs versioned with ``URLPathVersioning`` or ``NamespaceVersioning``
|
||||
- **ADDED:** added ability to recursively customize schema generation
|
||||
:ref:`using pluggable inspector classes <custom-spec-inspectors>`
|
||||
@@ -45,6 +341,8 @@ Changelog
|
||||
**1.0.6**
|
||||
*********
|
||||
|
||||
*Release date: Dec 23, 2017*
|
||||
|
||||
- **FIXED:** Swagger UI "Try it out!" should now work with Django login
|
||||
- **FIXED:** callable ``default`` values on serializer fields will now be properly called (:pr:`24`, :issue:`25`)
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.8.0
|
||||
@@ -56,6 +354,8 @@ Changelog
|
||||
**1.0.5**
|
||||
*********
|
||||
|
||||
*Release date: Dec 18, 2017*
|
||||
|
||||
- **FIXED:** fixed a crash caused by having read-only Serializers nested by reference
|
||||
- **FIXED:** removed erroneous backslashes in paths when routes are generated using Django 2
|
||||
`path() <https://docs.djangoproject.com/en/2.0/ref/urls/#django.urls.path>`_
|
||||
@@ -67,6 +367,8 @@ Changelog
|
||||
**1.0.4**
|
||||
*********
|
||||
|
||||
*Release date: Dec 16, 2017*
|
||||
|
||||
- **FIXED:** fixed improper generation of YAML references
|
||||
- **ADDED:** added ``query_serializer`` parameter to
|
||||
:func:`@swagger_auto_schema <.swagger_auto_schema>` (:issue:`16`, :pr:`17`)
|
||||
@@ -75,6 +377,8 @@ Changelog
|
||||
**1.0.3**
|
||||
*********
|
||||
|
||||
*Release date: Dec 15, 2017*
|
||||
|
||||
- **FIXED:** fixed bug that caused schema views returned from cache to fail (:issue:`14`)
|
||||
- **FIXED:** disabled automatic generation of response schemas for form operations to avoid confusing errors caused by
|
||||
attempting to shove file parameters into Schema objects
|
||||
@@ -83,4 +387,6 @@ Changelog
|
||||
**1.0.2**
|
||||
*********
|
||||
|
||||
*Release date: Dec 13, 2017*
|
||||
|
||||
- First published version
|
||||
|
||||
+26
-26
@@ -39,7 +39,7 @@ master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = 'drf-yasg'
|
||||
copyright = '2017, Cristi V.'
|
||||
copyright = '2018, Cristi V.'
|
||||
author = 'Cristi V.'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
@@ -162,6 +162,18 @@ autodoc_mock_imports = []
|
||||
|
||||
nitpick_ignore = [
|
||||
('py:class', 'object'),
|
||||
('py:class', 'bool'),
|
||||
('py:class', 'dict'),
|
||||
('py:class', 'list'),
|
||||
('py:class', 'str'),
|
||||
('py:class', 'int'),
|
||||
('py:class', 'bytes'),
|
||||
('py:class', 'tuple'),
|
||||
('py:class', 'callable'),
|
||||
('py:class', 'type'),
|
||||
('py:class', 'OrderedDict'),
|
||||
('py:class', 'None'),
|
||||
|
||||
('py:class', 'Exception'),
|
||||
('py:class', 'collections.OrderedDict'),
|
||||
|
||||
@@ -174,29 +186,17 @@ nitpick_ignore = [
|
||||
('py:class', 'OpenAPICodecJson'),
|
||||
('py:class', 'OpenAPISchemaGenerator'),
|
||||
|
||||
('py:obj', 'bool'),
|
||||
('py:obj', 'dict'),
|
||||
('py:obj', 'list'),
|
||||
('py:obj', 'str'),
|
||||
('py:obj', 'int'),
|
||||
('py:obj', 'bytes'),
|
||||
('py:obj', 'tuple'),
|
||||
('py:obj', 'callable'),
|
||||
('py:obj', 'type'),
|
||||
('py:obj', 'OrderedDict'),
|
||||
('py:obj', 'None'),
|
||||
|
||||
('py:obj', 'coreapi.Field'),
|
||||
('py:obj', 'BaseFilterBackend'),
|
||||
('py:obj', 'BasePagination'),
|
||||
('py:obj', 'Request'),
|
||||
('py:obj', 'rest_framework.request.Request'),
|
||||
('py:obj', 'rest_framework.serializers.Field'),
|
||||
('py:obj', 'serializers.Field'),
|
||||
('py:obj', 'serializers.BaseSerializer'),
|
||||
('py:obj', 'Serializer'),
|
||||
('py:obj', 'BaseSerializer'),
|
||||
('py:obj', 'APIView'),
|
||||
('py:class', 'coreapi.Field'),
|
||||
('py:class', 'BaseFilterBackend'),
|
||||
('py:class', 'BasePagination'),
|
||||
('py:class', 'Request'),
|
||||
('py:class', 'rest_framework.request.Request'),
|
||||
('py:class', 'rest_framework.serializers.Field'),
|
||||
('py:class', 'serializers.Field'),
|
||||
('py:class', 'serializers.BaseSerializer'),
|
||||
('py:class', 'Serializer'),
|
||||
('py:class', 'BaseSerializer'),
|
||||
('py:class', 'APIView'),
|
||||
]
|
||||
|
||||
# even though the package should be already installed, the sphinx build on RTD
|
||||
@@ -205,7 +205,7 @@ sys.path.insert(0, os.path.abspath('../src'))
|
||||
|
||||
# activate the Django testproj to be able to succesfully import drf_yasg
|
||||
sys.path.insert(0, os.path.abspath('../testproj'))
|
||||
os.putenv('DJANGO_SETTINGS_MODULE', 'testproj.settings')
|
||||
os.putenv('DJANGO_SETTINGS_MODULE', 'testproj.settings.local')
|
||||
|
||||
from django.conf import settings # noqa: E402
|
||||
|
||||
@@ -273,7 +273,7 @@ def role_github_user(name, rawtext, text, lineno, inliner, options=None, content
|
||||
options = options or {}
|
||||
content = content or []
|
||||
|
||||
if not re.match(r"^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$", text):
|
||||
if not re.match(r"^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$", text, re.IGNORECASE):
|
||||
return sphinx_err(inliner, lineno, rawtext, '"%s" is not a valid GitHub username.' % text)
|
||||
|
||||
ref = gh_user_uri.format(text)
|
||||
|
||||
+56
-121
@@ -9,125 +9,30 @@ Custom schema generation
|
||||
If the default spec generation does not quite match what you were hoping to achieve, ``drf-yasg`` provides some
|
||||
custom behavior hooks by default.
|
||||
|
||||
*********************
|
||||
Swagger spec overview
|
||||
*********************
|
||||
.. _custom-spec-excluding-endpoints:
|
||||
|
||||
This library generates OpenAPI 2.0 documents. The authoritative specification for this document's structure will always
|
||||
be the official documentation over at `swagger.io <https://swagger.io/>`__ and the `OpenAPI 2.0 specification
|
||||
page <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md>`__.
|
||||
*******************
|
||||
Excluding endpoints
|
||||
*******************
|
||||
|
||||
Beause the above specifications are a bit heavy and convoluted, here is a general overview of how the specification
|
||||
is structured, starting from the root ``Swagger`` object.
|
||||
You can prevent a view from being included in the Swagger view by setting its class-level ``swagger_schema``
|
||||
attribute to ``None``, or you can prevent an operation from being included by setting its ``auto_schema`` override
|
||||
to none in :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`:
|
||||
|
||||
* :class:`.Swagger` object
|
||||
+ ``info``, ``schemes``, ``securityDefinitions`` and other informative attributes
|
||||
+ ``paths``: :class:`.Paths` object
|
||||
A list of all the paths in the API in the form of a mapping
|
||||
.. code-block:: python
|
||||
|
||||
- ``{path}``: :class:`.PathItem` - each :class:`.PathItem` has multiple operations keyed by method
|
||||
* ``{http_method}``: :class:`.Operation`
|
||||
Each operation is thus uniquely identified by its ``(path, http_method)`` combination,
|
||||
e.g. ``GET /articles/``, ``POST /articles/``, etc.
|
||||
* ``parameters``: [:class:`.Parameter`] - and a list of path parameters
|
||||
+ ``definitions``: named Models
|
||||
A list of all the named models in the API in the form of a mapping
|
||||
class UserList(APIView):
|
||||
swagger_schema = None
|
||||
|
||||
- ``{ModelName}``: :class:`.Schema`
|
||||
|
||||
* :class:`.Operation` contains the following information about each operation:
|
||||
+ ``parameters``: [:class:`.Parameter`]
|
||||
A list of all the *query*, *header* and *form* parameters accepted by the operation.
|
||||
|
||||
- there can also be **at most one** body parameter whose structure is represented by a
|
||||
:class:`.Schema` or a reference to one (:class:`.SchemaRef`)
|
||||
+ ``responses``: :class:`.Responses`
|
||||
A list of all the possible responses the operation is expected to return. Each response can optionally have a
|
||||
:class:`.Schema` which describes the structure of its body.
|
||||
|
||||
- ``{status_code}``: :class:`.Response` - mapping of status code to response definition
|
||||
|
||||
+ ``operationId`` - should be unique across all operations
|
||||
+ ``tags`` - used to group operations in the listing
|
||||
|
||||
It is interesting to note the main differences between :class:`.Parameter` and :class:`.Schema` objects:
|
||||
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| :class:`.Schema` | :class:`.Parameter` |
|
||||
+==========================================================+===========================================================+
|
||||
| Can nest other Schemas | Cannot nest other Parameters |br| |
|
||||
| | Can only nest a Schema if the parameter is ``in: body`` |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot describe file uploads |br| | Can describe file uploads via ``type`` = ``file``, |br| |
|
||||
| - ``file`` is not permitted as a value for ``type`` | but only as part of a form :class:`.Operation` [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can be used in :class:`.Response`\ s | Cannot be used in :class:`.Response`\ s |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot be used in form :class:`.Operation`\ s [#formop]_ | Can be used in form :class:`.Operation`\ s [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can only describe request or response bodies | Can describe ``query``, ``form``, ``header`` or ``path`` |
|
||||
| | parameters |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
|
||||
.. [#formop] a form Operation is an :class:`.Operation` that consumes ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` content
|
||||
|
||||
* a form Operation cannot have ``body`` parameters
|
||||
* a non-form operation cannot have ``form`` parameters
|
||||
|
||||
****************
|
||||
Default behavior
|
||||
****************
|
||||
|
||||
This section describes where information is sourced from when using the default generation process.
|
||||
|
||||
* :class:`.Paths` are generated by exploring the patterns registered in your default ``urlconf``, or the ``patterns``
|
||||
and ``urlconf`` you specified when constructing :class:`.OpenAPISchemaGenerator`; only views inheriting from Django
|
||||
Rest Framework's ``APIView`` are looked at, all other views are ignored
|
||||
* ``path`` :class:`.Parameter`\ s are generated by looking in the URL pattern for any template parameters; attempts are
|
||||
made to guess their type from the views ``queryset`` and ``lookup_field``, if applicable. You can override path
|
||||
parameters via ``manual_parameters`` in :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
* ``query`` :class:`.Parameter`\ s - i.e. parameters specified in the URL as ``/path/?query1=value&query2=value`` -
|
||||
are generated from your view's ``filter_backends`` and ``paginator``, if any are declared. Additional parameters can
|
||||
be specified via the ``query_serializer`` and ``manual_parameters`` arguments of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`
|
||||
* The request body is only generated for the HTTP ``POST``, ``PUT`` and ``PATCH`` methods, and is sourced from the
|
||||
view's ``serializer_class``. You can also override the request body using the ``request_body`` argument of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
|
||||
- if the view represents a form request (that is, all its parsers are of the ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` media types), the request body will be output as ``form``
|
||||
:class:`.Parameter`\ s
|
||||
- if it is not a form request, the request body will be output as a single ``body`` :class:`.Parameter` wrapped
|
||||
around a :class:`.Schema`
|
||||
|
||||
* ``header`` :class:`.Parameter`\ s are supported by the OpenAPI specification but are never generated by this library;
|
||||
you can still add them using ``manual_parameters``.
|
||||
* :class:`.Responses` are generated as follows:
|
||||
|
||||
+ if ``responses`` is provided to :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>` and contains at least
|
||||
one success status code (i.e. any `2xx` status code), no automatic response is generated and the given response
|
||||
is used as described in the :func:`@swagger_auto_schema documentation <.swagger_auto_schema>`
|
||||
+ otherwise, an attempt is made to generate a default response:
|
||||
|
||||
- the success status code is assumed to be ``204` for ``DELETE`` requests, ``201`` for ``POST`` requests, and
|
||||
``200`` for all other request methods
|
||||
- if the view has a request body, the same ``Serializer`` or :class:`.Schema` as in the request body is used
|
||||
in generating the :class:`.Response` schema; this is inline with the default ``GenericAPIView`` and
|
||||
``GenericViewSet`` behavior
|
||||
- if the view has no request body, its ``serializer_class`` is used to generate the :class:`.Response` schema
|
||||
- if the view is a list view (as defined by :func:`.is_list_view`), the response schema is wrapped in an array
|
||||
- if the view is also paginated, the response schema is then wrapped in the appropriate paging response structure
|
||||
- the description of the response is left blank
|
||||
|
||||
* :class:`.Response` headers are supported by the OpenAPI specification but not currently supported by this library;
|
||||
you can still add them manually by providing an `appropriately structured dictionary
|
||||
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headersObject>`_
|
||||
to the ``headers`` property of a :class:`.Response` object
|
||||
* *descriptions* for :class:`.Operation`\ s, :class:`.Parameter`\ s and :class:`.Schema`\ s are picked up from
|
||||
docstrings and ``help_text`` attributes in the same manner as the `default DRF SchemaGenerator
|
||||
<http://www.django-rest-framework.org/api-guide/schemas/#schemas-as-documentation>`_
|
||||
# all methods of the UserList class will be excluded
|
||||
...
|
||||
|
||||
# only the GET method will be shown in Swagger
|
||||
@swagger_auto_schema(method='put', auto_schema=None)
|
||||
@swagger_auto_schema(methods=['get'], ...)
|
||||
@api_view(['GET', 'PUT'])
|
||||
def user_detail(request, pk):
|
||||
pass
|
||||
|
||||
.. _custom-spec-swagger-auto-schema:
|
||||
|
||||
@@ -182,8 +87,8 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
|
||||
|
||||
* for ``ViewSet``, ``GenericViewSet``, ``ModelViewSet``, because each viewset corresponds to multiple **paths**, you have
|
||||
to decorate the *action methods*, i.e. ``list``, ``create``, ``retrieve``, etc. |br|
|
||||
Additionally, ``@list_route``\ s or ``@detail_route``\ s defined on the viewset, like function based api views, can
|
||||
respond to multiple HTTP methods and thus have multiple operations that must be decorated separately:
|
||||
Additionally, ``@action``\ s, ``@list_route``\ s or ``@detail_route``\ s defined on the viewset, like function based
|
||||
api views, can respond to multiple HTTP methods and thus have multiple operations that must be decorated separately:
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
@@ -191,13 +96,13 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
|
||||
class ArticleViewSet(viewsets.ModelViewSet):
|
||||
# method or 'methods' can be skipped because the list_route only handles a single method (GET)
|
||||
@swagger_auto_schema(operation_description='GET /articles/today/')
|
||||
@list_route(methods=['get'])
|
||||
@action(detail=False, methods=['get'])
|
||||
def today(self, request):
|
||||
...
|
||||
|
||||
@swagger_auto_schema(method='get', operation_description="GET /articles/{id}/image/")
|
||||
@swagger_auto_schema(method='post', operation_description="POST /articles/{id}/image/")
|
||||
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
|
||||
@action(detail=True, methods=['get', 'post'], parser_classes=(MultiPartParser,))
|
||||
def image(self, request, id=None):
|
||||
...
|
||||
|
||||
@@ -264,10 +169,20 @@ You can define some per-serializer options by adding a ``Meta`` class to your se
|
||||
class Meta:
|
||||
... options here ...
|
||||
|
||||
Currently, the only option you can add here is
|
||||
.. _swagger_schema_fields:
|
||||
|
||||
The available options are:
|
||||
|
||||
* ``ref_name`` - a string which will be used as the model definition name for this serializer class; setting it to
|
||||
``None`` will force the serializer to be generated as an inline model everywhere it is used
|
||||
``None`` will force the serializer to be generated as an inline model everywhere it is used. If two serializers
|
||||
have the same ``ref_name``, both their usages will be replaced with a reference to the same definition.
|
||||
If this option is not specified, all serializers have an implicit name derived from their class name, minus any
|
||||
``Serializer`` suffix (e.g. ``UserSerializer`` -> ``User``, ``SerializerWithSuffix`` -> ``SerializerWithSuffix``)
|
||||
* ``swagger_schema_fields`` - a dictionary mapping :class:`.Schema` field names to values. These attributes
|
||||
will be set on the :class:`.Schema` object generated from the ``Serializer``. Field names must be python values,
|
||||
which are converted to Swagger ``Schema`` attribute names according to :func:`.make_swagger_name`.
|
||||
Attribute names and values must conform to the `OpenAPI 2.0 specification <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject>`_.
|
||||
|
||||
|
||||
*************************
|
||||
Subclassing and extending
|
||||
@@ -320,8 +235,6 @@ This custom generator can be put to use by setting it as the :attr:`.generator_c
|
||||
``Inspector`` classes
|
||||
---------------------
|
||||
|
||||
.. versionadded:: 1.1
|
||||
|
||||
For customizing behavior related to specific field, serializer, filter or paginator classes you can implement the
|
||||
:class:`~.inspectors.FieldInspector`, :class:`~.inspectors.SerializerInspector`, :class:`~.inspectors.FilterInspector`,
|
||||
:class:`~.inspectors.PaginatorInspector` classes and use them with
|
||||
@@ -398,3 +311,25 @@ A second example, of a :class:`~.inspectors.FieldInspector` that removes the ``t
|
||||
This means that you should generally avoid view or method-specific ``FieldInspector``\ s if you are dealing with
|
||||
references (a.k.a named models), because you can never know which view will be the first to generate the schema
|
||||
for a given serializer.
|
||||
|
||||
**IMPORTANT:** nested fields on ``ModelSerializer``\ s that are generated from model ``ForeignKeys`` will always be
|
||||
output by value. If you want the by-reference behaviour you have to explictly set the serializer class of nested
|
||||
fields instead of letting ``ModelSerializer`` generate one automatically; for example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class OneSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = SomeModel
|
||||
fields = ('id',)
|
||||
|
||||
|
||||
class AnotherSerializer(serializers.ModelSerializer):
|
||||
chilf = OneSerializer()
|
||||
|
||||
class Meta:
|
||||
model = SomeParentModel
|
||||
fields = ('id', 'child')
|
||||
|
||||
Another caveat that stems from this is that any serializer named "``NestedSerializer``" will be forced inline
|
||||
unless it has a ``ref_name`` set explicitly.
|
||||
|
||||
@@ -12,6 +12,8 @@ drf-yasg
|
||||
|
||||
readme.rst
|
||||
rendering.rst
|
||||
openapi.rst
|
||||
security.rst
|
||||
custom_spec.rst
|
||||
custom_ui.rst
|
||||
settings.rst
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
.. |br| raw:: html
|
||||
|
||||
<br />
|
||||
|
||||
**********************
|
||||
Functional overview
|
||||
**********************
|
||||
|
||||
------------------------------
|
||||
OpenAPI specification overview
|
||||
------------------------------
|
||||
|
||||
This library generates OpenAPI 2.0 documents. The authoritative specification for this document's structure will always
|
||||
be the official documentation over at `swagger.io <https://swagger.io/>`__ and the `OpenAPI 2.0 specification
|
||||
page <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md>`__.
|
||||
|
||||
Beause the above specifications are a bit heavy and convoluted, here is a general overview of how the specification
|
||||
is structured, starting from the root ``Swagger`` object.
|
||||
|
||||
* :class:`.Swagger` object
|
||||
+ ``info``, ``schemes``, ``securityDefinitions`` and other informative attributes
|
||||
+ ``paths``: :class:`.Paths` object
|
||||
A list of all the paths in the API in the form of a mapping
|
||||
|
||||
- ``{path}``: :class:`.PathItem` - each :class:`.PathItem` has multiple operations keyed by method
|
||||
* ``{http_method}``: :class:`.Operation`
|
||||
Each operation is thus uniquely identified by its ``(path, http_method)`` combination,
|
||||
e.g. ``GET /articles/``, ``POST /articles/``, etc.
|
||||
* ``parameters``: [:class:`.Parameter`] - and a list of path parameters
|
||||
+ ``definitions``: named Models
|
||||
A list of all the named models in the API in the form of a mapping
|
||||
|
||||
- ``{ModelName}``: :class:`.Schema`
|
||||
|
||||
* :class:`.Operation` contains the following information about each operation:
|
||||
+ ``parameters``: [:class:`.Parameter`]
|
||||
A list of all the *query*, *header* and *form* parameters accepted by the operation.
|
||||
|
||||
- there can also be **at most one** body parameter whose structure is represented by a
|
||||
:class:`.Schema` or a reference to one (:class:`.SchemaRef`)
|
||||
+ ``responses``: :class:`.Responses`
|
||||
A list of all the possible responses the operation is expected to return. Each response can optionally have a
|
||||
:class:`.Schema` which describes the structure of its body.
|
||||
|
||||
- ``{status_code}``: :class:`.Response` - mapping of status code to response definition
|
||||
|
||||
+ ``operationId`` - should be unique across all operations
|
||||
+ ``tags`` - used to group operations in the listing
|
||||
|
||||
It is interesting to note the main differences between :class:`.Parameter` and :class:`.Schema` objects:
|
||||
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| :class:`.Schema` | :class:`.Parameter` |
|
||||
+==========================================================+===========================================================+
|
||||
| Can nest other Schemas | Cannot nest other Parameters |br| |
|
||||
| | Can only nest a Schema if the parameter is ``in: body`` |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot describe file uploads |br| | Can describe file uploads via ``type`` = ``file``, |br| |
|
||||
| - ``file`` is not permitted as a value for ``type`` | but only as part of a form :class:`.Operation` [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can be used in :class:`.Response`\ s | Cannot be used in :class:`.Response`\ s |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot be used in form :class:`.Operation`\ s [#formop]_ | Can be used in form :class:`.Operation`\ s [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can only describe request or response bodies | Can describe ``query``, ``form``, ``header`` or ``path`` |
|
||||
| | parameters |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
|
||||
.. [#formop] a form Operation is an :class:`.Operation` that consumes ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` content
|
||||
|
||||
* a form Operation cannot have ``body`` parameters
|
||||
* a non-form operation cannot have ``form`` parameters
|
||||
|
||||
----------------
|
||||
Default behavior
|
||||
----------------
|
||||
|
||||
This section describes where information is sourced from when using the default generation process.
|
||||
|
||||
* :class:`.Paths` are generated by exploring the patterns registered in your default ``urlconf``, or the ``patterns``
|
||||
and ``urlconf`` you specified when constructing :class:`.OpenAPISchemaGenerator`; only views inheriting from Django
|
||||
Rest Framework's ``APIView`` are looked at, all other views are ignored
|
||||
* ``path`` :class:`.Parameter`\ s are generated by looking in the URL pattern for any template parameters; attempts are
|
||||
made to guess their type from the views ``queryset`` and ``lookup_field``, if applicable. You can override path
|
||||
parameters via ``manual_parameters`` in :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
* ``query`` :class:`.Parameter`\ s - i.e. parameters specified in the URL as ``/path/?query1=value&query2=value`` -
|
||||
are generated from your view's ``filter_backends`` and ``paginator``, if any are declared. Additional parameters can
|
||||
be specified via the ``query_serializer`` and ``manual_parameters`` arguments of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`
|
||||
* The request body is only generated for the HTTP ``POST``, ``PUT`` and ``PATCH`` methods, and is sourced from the
|
||||
view's ``serializer_class``. You can also override the request body using the ``request_body`` argument of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
|
||||
- if the view represents a form request (that is, all its parsers are of the ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` media types), the request body will be output as ``form``
|
||||
:class:`.Parameter`\ s
|
||||
- if it is not a form request, the request body will be output as a single ``body`` :class:`.Parameter` wrapped
|
||||
around a :class:`.Schema`
|
||||
|
||||
* ``header`` :class:`.Parameter`\ s are supported by the OpenAPI specification but are never generated by this library;
|
||||
you can still add them using ``manual_parameters``.
|
||||
* :class:`.Responses` are generated as follows:
|
||||
|
||||
+ if ``responses`` is provided to :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>` and contains at least
|
||||
one success status code (i.e. any `2xx` status code), no automatic response is generated and the given response
|
||||
is used as described in the :func:`@swagger_auto_schema documentation <.swagger_auto_schema>`
|
||||
+ otherwise, an attempt is made to generate a default response:
|
||||
|
||||
- the success status code is assumed to be ``204` for ``DELETE`` requests, ``201`` for ``POST`` requests, and
|
||||
``200`` for all other request methods
|
||||
- if the view has a request body, the same ``Serializer`` or :class:`.Schema` as in the request body is used
|
||||
in generating the :class:`.Response` schema; this is inline with the default ``GenericAPIView`` and
|
||||
``GenericViewSet`` behavior
|
||||
- if the view has no request body, its ``serializer_class`` is used to generate the :class:`.Response` schema
|
||||
- if the view is a list view (as defined by :func:`.is_list_view`), the response schema is wrapped in an array
|
||||
- if the view is also paginated, the response schema is then wrapped in the appropriate paging response structure
|
||||
- the description of the response is left blank
|
||||
|
||||
* :class:`.Response` headers are supported by the OpenAPI specification but not currently supported by this library;
|
||||
you can still add them manually by providing an `appropriately structured dictionary
|
||||
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headersObject>`_
|
||||
to the ``headers`` property of a :class:`.Response` object
|
||||
* *descriptions* for :class:`.Operation`\ s, :class:`.Parameter`\ s and :class:`.Schema`\ s are picked up from
|
||||
docstrings and ``help_text`` attributes in the same manner as the `default DRF SchemaGenerator
|
||||
<http://www.django-rest-framework.org/api-guide/schemas/#schemas-as-documentation>`_
|
||||
* .. _custom-spec-base-url:
|
||||
|
||||
The base URL for the API consists of three values - the ``host``, ``schemes`` and ``basePath`` attributes
|
||||
* The host name and scheme are determined, in descending order of priority:
|
||||
|
||||
+ from the ``url`` argument passed to :func:`.get_schema_view` (more specifically, to the underlying
|
||||
:class:`.OpenAPISchemaGenerator`)
|
||||
+ from the :ref:`DEFAULT_API_URL setting <default-swagger-settings>`
|
||||
+ inferred from the request made to the schema endpoint
|
||||
|
||||
For example, an url of ``https://www.example.com:8080/some/path`` will populate the ``host`` and ``schemes``
|
||||
attributes with ``www.example.com:8080`` and ``['https']``, respectively. The path component will be ignored.
|
||||
* The base path is determined as the concatenation of two variables:
|
||||
|
||||
#. the `SCRIPT_NAME`_ wsgi environment variable; this is set, for example, when serving the site from a
|
||||
sub-path using web server url rewriting
|
||||
|
||||
.. Tip::
|
||||
|
||||
The Django `FORCE_SCRIPT_NAME`_ setting can be used to override the `SCRIPT_NAME`_ or set it when it's
|
||||
missing from the environment.
|
||||
|
||||
#. the longest common path prefix of all the urls in your API - see :meth:`.determine_path_prefix`
|
||||
|
||||
* When using API versioning with ``NamespaceVersioning`` or ``URLPathVersioning``, versioned endpoints that do not
|
||||
match the version used to access the ``SchemaView`` will be excluded from the endpoint list - for example,
|
||||
``/api/v1.0/endpoint`` will be shown when viewing ``/api/v1.0/swagger/``, while ``/api/v2.0/endpoint`` will not
|
||||
|
||||
Other versioning schemes are not presently supported.
|
||||
|
||||
---------------------
|
||||
A note on limitations
|
||||
---------------------
|
||||
|
||||
When schema generation is requested, available endpoints are inspected by enumeration all the routes registered in
|
||||
Django's urlconf. Each registered view is then artificially instantiated for introspection, and it is this step that
|
||||
brings some limitations to what can be done:
|
||||
|
||||
* the ``request`` the view sees will always be the request made against the schema view endpoint
|
||||
- e.g. ``GET /swagger.yaml``
|
||||
* path parameters will not be filled
|
||||
|
||||
This means that you could get surprizing results if your ``get_serializer`` or ``get_serializer_class`` methods
|
||||
depend on the incoming request, call ``get_object`` or in general depend on any stateful logic. You can prevent this
|
||||
in a few ways:
|
||||
|
||||
* provide a fixed serializer for request and response body introspection using
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`, to prevent ``get_serializer`` from being called on
|
||||
the view
|
||||
* :ref:`exclude your endpoint from introspection <custom-spec-excluding-endpoints>`
|
||||
* use the ``swagger_fake_view`` marker to detect requests generated by ``drf-yasg``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_serializer_class(self):
|
||||
if getattr(self, 'swagger_fake_view', False):
|
||||
return TodoTreeSerializer
|
||||
|
||||
raise NotImplementedError("must not call this")
|
||||
|
||||
.. _SCRIPT_NAME: https://www.python.org/dev/peps/pep-0333/#environ-variables
|
||||
.. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name
|
||||
+2
-4
@@ -41,8 +41,6 @@ You can use your custom renderer classes as kwargs to :meth:`.SchemaView.as_cach
|
||||
Management command
|
||||
******************
|
||||
|
||||
.. versionadded:: 1.1.1
|
||||
|
||||
If you only need a swagger spec file in YAML or JSON format, you can use the ``generate_swagger`` management command
|
||||
to get it without having to start the web server:
|
||||
|
||||
@@ -66,7 +64,7 @@ See the command help for more advanced options:
|
||||
|
||||
In ``settings.py``:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'DEFAULT_INFO': 'import.path.to.urls.api_info',
|
||||
@@ -74,7 +72,7 @@ See the command help for more advanced options:
|
||||
|
||||
In ``urls.py``:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
api_info = openapi.Info(
|
||||
title="Snippets API",
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
*********************************
|
||||
Describing authentication schemes
|
||||
*********************************
|
||||
|
||||
When using the `swagger-ui` frontend, it is possible to interact with the API described by your Swagger document.
|
||||
This interaction might require authentication, which you will have to describe in order to make `swagger-ui` work
|
||||
with it.
|
||||
|
||||
|
||||
--------------------
|
||||
Security definitions
|
||||
--------------------
|
||||
|
||||
The first step that you have to do is add a :ref:`SECURITY_DEFINITIONS <security-definitions-settings>` setting
|
||||
to declare all authentication schemes supported by your API.
|
||||
|
||||
For example, the definition for a simple API accepting HTTP basic auth and `Authorization` header API tokens would be:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'Basic': {
|
||||
'type': 'basic'
|
||||
},
|
||||
'Bearer': {
|
||||
'type': 'apiKey',
|
||||
'name': 'Authorization',
|
||||
'in': 'header'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
---------------------
|
||||
Security requirements
|
||||
---------------------
|
||||
|
||||
The second step is specifying, for each endpoint, which authentication mechanism can be used for interacting with it.
|
||||
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object for details.
|
||||
|
||||
By default, a top-level `security` that accepts any one of the declared security definitions is generated.
|
||||
For the example above, that would be :code:`[{'Basic': []}, {'Bearer': []}]`. This can be overriden using the
|
||||
:ref:`SECURITY_REQUIREMENTS <security-definitions-settings>` setting.
|
||||
|
||||
Operation-level overrides can be added using the ``security`` parameter of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
|
||||
|
||||
-------------------------------
|
||||
``swagger-ui`` as OAuth2 client
|
||||
-------------------------------
|
||||
|
||||
It is possible to configure ``swagger-ui`` to authenticate against your (or a third party) OAuth2 service when sending
|
||||
"Try it out" requests. This client-side configuration does not remove the requirement of a spec-side
|
||||
:ref:`security definiiton <security-definitions-settings>`, but merely allows you to test OAuth2 APIs using
|
||||
``swagger-ui`` as a client.
|
||||
|
||||
**DISCLAIMER**: this setup is very poorly tested as I do not currently implement OAuth in any of my projects. All
|
||||
contributions relating to documentation, bugs, mistakes or anything else are welcome as an issue or pull request. The
|
||||
settings described below were added as a result of discussion in issue :issue:`53`.
|
||||
|
||||
The settings of interest can be found on the :ref:`settings page <oauth2-settings>`. Configuration options are similar
|
||||
to most OAuth client setups like web or mobile applications. Reading the relevant ``swagger-ui`` docmentation linked
|
||||
will also probably help.
|
||||
|
||||
|
||||
Example
|
||||
^^^^^^^
|
||||
|
||||
A very simple working configuration was provided by :ghuser:`Vigrond`, originally at
|
||||
`https://github.com/Vigrond/django_oauth2_example <https://github.com/Vigrond/django_oauth2_example>`_.
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'USE_SESSION_AUTH': False,
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'Your App API - Swagger': {
|
||||
'type': 'oauth2',
|
||||
'authorizationUrl': '/yourapp/o/authorize',
|
||||
'tokenUrl': '/yourapp/o/token/',
|
||||
'flow": "accessCode',
|
||||
'scopes': {
|
||||
'read:groups': 'read groups',
|
||||
}
|
||||
}
|
||||
},
|
||||
'OAUTH2_CONFIG': {
|
||||
'clientId': 'yourAppClientId',
|
||||
'clientSecret': 'yourAppClientSecret',
|
||||
'appName': 'your application name'
|
||||
},
|
||||
}
|
||||
|
||||
If the OAuth2 provider requires you to provide the full absolute redirect URL, the default value for most
|
||||
``staticfiles`` configurations will be ``<origin>/static/drf-yasg/swagger-ui-dist/oauth2-redirect.html``. If this is
|
||||
not suitable for some reason, you can override the ``OAUTH2_REDIRECT_URL`` setting as appropriate.
|
||||
+80
-13
@@ -43,6 +43,14 @@ The possible settings and their default values are as follows:
|
||||
Default classes
|
||||
===============
|
||||
|
||||
DEFAULT_GENERATOR_CLASS
|
||||
-------------------------
|
||||
|
||||
:class:`~.generators.OpenAPISchemaGenerator` subclass that will be used by default for generating the final
|
||||
:class:`.Schema` object. Can be overriden by the ``generator_class`` argument to :func:`.get_schema_view`.
|
||||
|
||||
**Default**: :class:`drf_yasg.generators.OpenAPISchemaGenerator`
|
||||
|
||||
DEFAULT_AUTO_SCHEMA_CLASS
|
||||
-------------------------
|
||||
|
||||
@@ -66,6 +74,8 @@ to this list.
|
||||
:class:`'drf_yasg.inspectors.ChoiceFieldInspector' <.inspectors.ChoiceFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.FileFieldInspector' <.inspectors.FileFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.DictFieldInspector' <.inspectors.DictFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.HiddenFieldInspector' <.inspectors.HiddenFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.RecursiveFieldInspector' <.inspectors.RecursiveFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \
|
||||
``]``
|
||||
@@ -100,17 +110,20 @@ DEFAULT_INFO
|
||||
------------
|
||||
|
||||
An import string to an :class:`.openapi.Info` object. This will be used when running the ``generate_swagger``
|
||||
management command, or if no ``info`` argument is passed to ``get_schema_view``.
|
||||
management command, or if no ``info`` argument is passed to :func:`.get_schema_view`.
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
DEFAULT_API_URL
|
||||
---------------
|
||||
|
||||
A string representing the default API URL. This will be used to populate the ``host``, ``schemes`` and ``basePath``
|
||||
attributes of the Swagger document if no API URL is otherwise provided.
|
||||
A string representing the default API URL. This will be used to populate the ``host`` and ``schemes`` attributes
|
||||
of the Swagger document if no API URL is otherwise provided. The Django `FORCE_SCRIPT_NAME`_ setting can be used for
|
||||
providing an API mount point prefix.
|
||||
|
||||
**Default**: :python:`''`
|
||||
See also: :ref:`documentation on base URL construction <custom-spec-base-url>`
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
Authorization
|
||||
=============
|
||||
@@ -137,6 +150,9 @@ URL for the Django Logout action when using `USE_SESSION_AUTH`_.
|
||||
|
||||
**Default**: :python:`django.conf.settings.LOGOUT_URL`
|
||||
|
||||
.. _security-definitions-settings:
|
||||
|
||||
|
||||
SECURITY_DEFINITIONS
|
||||
--------------------
|
||||
|
||||
@@ -151,6 +167,14 @@ See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#sec
|
||||
'type': 'basic'
|
||||
}
|
||||
|
||||
SECURITY_REQUIREMENTS
|
||||
---------------------
|
||||
|
||||
Global security requirements. If :python:`None`, all schemes in ``SECURITY_DEFINITIONS`` are accepted. |br|
|
||||
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject.
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
.. _swagger-ui-settings:
|
||||
|
||||
Swagger UI settings
|
||||
@@ -175,8 +199,8 @@ OPERATIONS_SORTER
|
||||
Sorting order for the operation list of each tag.
|
||||
|
||||
* :python:`None`: show in the order returned by the server
|
||||
* :python:`alpha`: sort alphabetically by path
|
||||
* :python:`method`: sort by HTTP method
|
||||
* :python:`'alpha'`: sort alphabetically by path
|
||||
* :python:`'method'`: sort by HTTP method
|
||||
|
||||
**Default**: :python:`None` |br|
|
||||
*Maps to parameter*: ``operationsSorter``
|
||||
@@ -187,7 +211,7 @@ TAGS_SORTER
|
||||
Sorting order for tagged operation groups.
|
||||
|
||||
* :python:`None`: Swagger UI default ordering
|
||||
* :python:`alpha`: sort alphabetically
|
||||
* :python:`'alpha'`: sort alphabetically
|
||||
|
||||
**Default**: :python:`None` |br|
|
||||
*Maps to parameter*: ``tagsSorter``
|
||||
@@ -197,9 +221,9 @@ DOC_EXPANSION
|
||||
|
||||
Controls the default expansion setting for the operations and tags.
|
||||
|
||||
* :python:`None`: everything is collapsed
|
||||
* :python:`list`: only tags are expanded
|
||||
* :python:`full`: all operations are expanded
|
||||
* :python:`'none'`: everything is collapsed
|
||||
* :python:`'list'`: only tags are expanded
|
||||
* :python:`'full'`: all operations are expanded
|
||||
|
||||
**Default**: :python:`'list'` |br|
|
||||
*Maps to parameter*: ``docExpansion``
|
||||
@@ -225,8 +249,8 @@ DEFAULT_MODEL_RENDERING
|
||||
|
||||
Controls whether operations show the model structure or the example value by default.
|
||||
|
||||
* :python:`model`: show the model fields by default
|
||||
* :python:`example`: show the example value by default
|
||||
* :python:`'model'`: show the model fields by default
|
||||
* :python:`'example'`: show the example value by default
|
||||
|
||||
**Default**: :python:`'model'` |br|
|
||||
*Maps to parameter*: ``defaultModelRendering``
|
||||
@@ -239,6 +263,46 @@ Controls how many levels are expaned by default when showing nested models.
|
||||
**Default**: :python:`3` |br|
|
||||
*Maps to parameter*: ``defaultModelExpandDepth``
|
||||
|
||||
SHOW_COMMON_EXTENSIONS
|
||||
----------------------
|
||||
|
||||
Controls the display of extensions (``pattern``, ``maxLength``, ``minLength``, ``maximum``, ``minimum``) fields and
|
||||
values for Parameters.
|
||||
|
||||
**Default**: :python:`True` |br|
|
||||
*Maps to parameter*: ``showCommonExtensions``
|
||||
|
||||
.. _oauth2-settings:
|
||||
|
||||
OAUTH2_REDIRECT_URL
|
||||
-------------------
|
||||
|
||||
Used when OAuth2 authenitcation of API requests via swagger-ui is desired. If ``None`` is passed, the
|
||||
``oauth2RedirectUrl`` parameter will be set to ``{% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}``. This
|
||||
is the default `https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html <oauth2-redirect>`_
|
||||
file provided by ``swagger-ui``.
|
||||
|
||||
**Default**: :python:`None` |br|
|
||||
*Maps to parameter*: ``oauth2RedirectUrl``
|
||||
|
||||
OAUTH2_CONFIG
|
||||
-------------
|
||||
|
||||
Used when OAuth2 authenitcation of API requests via swagger-ui is desired. Provides OAuth2 configuration parameters
|
||||
to the ``SwaggerUIBundle#initOAuth`` method, and must be a dictionary. See
|
||||
`OAuth2 configuration <https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/oauth2.md>`_.
|
||||
|
||||
**Default**: :python:`{}`
|
||||
|
||||
SUPPORTED_SUBMIT_METHODS
|
||||
------------------------
|
||||
|
||||
List of HTTP methods that have the Try it out feature enabled. An empty array disables Try it out for all operations.
|
||||
This does not filter the operations from the display.
|
||||
|
||||
**Default**: :python:`['get','put','post','delete','options','head','patch','trace']` |br|
|
||||
*Maps to parameter*: ``supportedSubmitMethods``
|
||||
|
||||
******************
|
||||
``REDOC_SETTINGS``
|
||||
******************
|
||||
@@ -249,7 +313,7 @@ ReDoc UI settings
|
||||
=================
|
||||
|
||||
ReDoc UI configuration settings. |br|
|
||||
See https://github.com/Rebilly/ReDoc#redoc-tag-attributes.
|
||||
See https://github.com/Rebilly/ReDoc#configuration.
|
||||
|
||||
LAZY_RENDERING
|
||||
--------------
|
||||
@@ -274,3 +338,6 @@ PATH_IN_MIDDLE
|
||||
|
||||
**Default**: :python:`False` |br|
|
||||
*Maps to attribute*: ``path-in-middle-panel``
|
||||
|
||||
|
||||
.. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name
|
||||
|
||||
Generated
+395
-242
@@ -4,54 +4,72 @@
|
||||
"lockfileVersion": 1,
|
||||
"dependencies": {
|
||||
"argparse": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz",
|
||||
"integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=",
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
|
||||
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
|
||||
"requires": {
|
||||
"sprintf-js": "1.0.3"
|
||||
"sprintf-js": "~1.0.2"
|
||||
}
|
||||
},
|
||||
"autolinker": {
|
||||
"version": "0.15.3",
|
||||
"resolved": "https://registry.npmjs.org/autolinker/-/autolinker-0.15.3.tgz",
|
||||
"integrity": "sha1-NCQX2PLzRhsUzwkIjV7fh5HcmDI="
|
||||
"asap": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
|
||||
"integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY="
|
||||
},
|
||||
"builtin-status-codes": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz",
|
||||
"integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug="
|
||||
"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": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.1.tgz",
|
||||
"integrity": "sha1-JtII6onje1y95gJQoV8DHBak1ms="
|
||||
},
|
||||
"classnames": {
|
||||
"version": "2.2.6",
|
||||
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.2.6.tgz",
|
||||
"integrity": "sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q=="
|
||||
},
|
||||
"clipboard": {
|
||||
"version": "1.7.1",
|
||||
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-1.7.1.tgz",
|
||||
"integrity": "sha1-Ng1taUbpmnof7zleQrqStem1oWs=",
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.1.tgz",
|
||||
"integrity": "sha512-7yhQBmtN+uYZmfRjjVjKa0dZdWuabzpSKGtyQZN+9C8xlC788SSJjOHWh7tzurfwTqTD5UDYAhIv5fRJg3sHjQ==",
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"good-listener": "1.2.2",
|
||||
"select": "1.1.2",
|
||||
"tiny-emitter": "2.0.2"
|
||||
"good-listener": "^1.2.2",
|
||||
"select": "^1.1.2",
|
||||
"tiny-emitter": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"commander": {
|
||||
"version": "2.12.2",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.12.2.tgz",
|
||||
"integrity": "sha512-BFnaq5ZOGcDN7FlrtBT4xxkgIToalIIxwjxLWVJ8bGTpe1LroqMiqQXdA7ygc7CRvaYS+9zfPGFnJqFSayx+AA==",
|
||||
"optional": true
|
||||
},
|
||||
"core-js": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/core-js/-/core-js-2.5.3.tgz",
|
||||
"integrity": "sha1-isw4NFgk8W2DZbfJtCWRaOjtYD4="
|
||||
"version": "1.2.7",
|
||||
"resolved": "https://registry.npmjs.org/core-js/-/core-js-1.2.7.tgz",
|
||||
"integrity": "sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY="
|
||||
},
|
||||
"core-util-is": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
|
||||
"integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
|
||||
"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",
|
||||
@@ -61,26 +79,63 @@
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"decko": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/decko/-/decko-1.2.0.tgz",
|
||||
"integrity": "sha1-/UPHNelnuAEzBohKVvvmZZlraBc="
|
||||
},
|
||||
"delegate": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/delegate/-/delegate-3.2.0.tgz",
|
||||
"integrity": "sha512-IofjkYBZaZivn0V8nnsMJGBr4jVLxHDheKSW88PyxS5QC4Vo9ZbZVvhzlSxY87fVq3STR6r+4cGepyHkcWOQSw==",
|
||||
"optional": true
|
||||
},
|
||||
"dropkickjs": {
|
||||
"version": "2.1.10",
|
||||
"resolved": "https://registry.npmjs.org/dropkickjs/-/dropkickjs-2.1.10.tgz",
|
||||
"integrity": "sha1-8TyUAhQdoJ50rfTmN5jXkiBEOPI="
|
||||
"dom-walk": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.1.tgz",
|
||||
"integrity": "sha1-ZyIm3HTI95mtNTB9+TaroRrNYBg="
|
||||
},
|
||||
"es6-promise": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.1.1.tgz",
|
||||
"integrity": "sha512-OaU1hHjgJf+b0NzsxCg7NdIYERD6Hy/PEmFLTjw+b65scuisG3Kt4QoTvJ66BBkPZ581gr0kpoVzKnxniM8nng=="
|
||||
"dompurify": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-1.0.7.tgz",
|
||||
"integrity": "sha512-1xK0JEda/jvIm3SgqHXKvRCh3AbEKCyBbUAGpNCMVIljBD145cPvBR66JSj3O4SdscFUx5NXsDkJpz6vDT8KLg=="
|
||||
},
|
||||
"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": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz",
|
||||
"integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw=="
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
|
||||
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="
|
||||
},
|
||||
"eventemitter3": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.0.tgz",
|
||||
"integrity": "sha512-ivIvhpq/Y0uSjcHDcOIccjmYjGLcP09MFGE7ysAwkAvkXfpZlC985pH2/ui64DKazbTW/4kN3yqozUxlXzI6cA=="
|
||||
},
|
||||
"fast-levenshtein": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
|
||||
"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": {
|
||||
"version": "2.0.5",
|
||||
@@ -92,42 +147,73 @@
|
||||
"resolved": "https://registry.npmjs.org/format-util/-/format-util-1.0.3.tgz",
|
||||
"integrity": "sha1-Ay3KShFiYqEsQ/TD7IVmQWxbLZU="
|
||||
},
|
||||
"global": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/global/-/global-4.3.2.tgz",
|
||||
"integrity": "sha1-52mJJopsdMOJCLEwWxD8DjlOnQ8=",
|
||||
"requires": {
|
||||
"min-document": "^2.19.0",
|
||||
"process": "~0.5.1"
|
||||
}
|
||||
},
|
||||
"good-listener": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/good-listener/-/good-listener-1.2.2.tgz",
|
||||
"integrity": "sha1-1TswzfkxPf+33JoNR3CWqm0UXFA=",
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"delegate": "3.2.0"
|
||||
"delegate": "^3.1.2"
|
||||
}
|
||||
},
|
||||
"hint.css": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/hint.css/-/hint.css-2.5.0.tgz",
|
||||
"integrity": "sha1-OMrjZn5C2R392+UDEAqzSTL2/WU="
|
||||
},
|
||||
"https-browserify": {
|
||||
"has-flag": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz",
|
||||
"integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM="
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-1.0.0.tgz",
|
||||
"integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo="
|
||||
},
|
||||
"inherits": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
|
||||
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
|
||||
"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=="
|
||||
},
|
||||
"isarray": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
|
||||
"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": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
|
||||
},
|
||||
"js-yaml": {
|
||||
"version": "3.10.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.10.0.tgz",
|
||||
"integrity": "sha512-O2v52ffjLa9VeM43J4XocZE//WT9N0IiwDa3KSHH7Tu8CtH+1qM8SIZvnsTh6v+4yFy5KUY3BHUVwjpfAWsjIA==",
|
||||
"version": "3.12.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz",
|
||||
"integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==",
|
||||
"requires": {
|
||||
"argparse": "1.0.9",
|
||||
"esprima": "4.0.0"
|
||||
"argparse": "^1.0.7",
|
||||
"esprima": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"json-pointer": {
|
||||
@@ -135,145 +221,219 @@
|
||||
"resolved": "https://registry.npmjs.org/json-pointer/-/json-pointer-0.6.0.tgz",
|
||||
"integrity": "sha1-jlAFUKaqxUZKRzN32leqbMIoKNc=",
|
||||
"requires": {
|
||||
"foreach": "2.0.5"
|
||||
"foreach": "^2.0.4"
|
||||
}
|
||||
},
|
||||
"json-schema-ref-parser": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-3.3.1.tgz",
|
||||
"integrity": "sha512-stQTMhec2R/p2L9dH4XXRlpNCP0mY8QrLd/9Kl+8SHJQmwHtE1nDfXH4wbsSM+GkJMl8t92yZbI0OIol432CIQ==",
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-5.1.2.tgz",
|
||||
"integrity": "sha512-gP0mSqqkG99xNeA4F6bf2pXQYv5fFqe9SybbKO9qSMmyzzfFFIqd16s9Y65mRWKzZ0muTjyEtcSE/hLZLvIjZw==",
|
||||
"requires": {
|
||||
"call-me-maybe": "1.0.1",
|
||||
"debug": "3.1.0",
|
||||
"es6-promise": "4.1.1",
|
||||
"js-yaml": "3.10.0",
|
||||
"ono": "4.0.2",
|
||||
"z-schema": "3.19.0"
|
||||
"call-me-maybe": "^1.0.1",
|
||||
"debug": "^3.1.0",
|
||||
"js-yaml": "^3.12.0",
|
||||
"ono": "^4.0.5"
|
||||
}
|
||||
},
|
||||
"lodash.get": {
|
||||
"version": "4.4.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz",
|
||||
"integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk="
|
||||
},
|
||||
"lodash.isequal": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
|
||||
"integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA="
|
||||
"loose-envify": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
||||
"requires": {
|
||||
"js-tokens": "^3.0.0 || ^4.0.0"
|
||||
}
|
||||
},
|
||||
"lunr": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lunr/-/lunr-1.0.0.tgz",
|
||||
"integrity": "sha1-XJJ2ySyRrDWpJBtQGNRnI9kuL18="
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.1.tgz",
|
||||
"integrity": "sha1-ETYWorYC3cEJMqe/ik5uV+v+zfI="
|
||||
},
|
||||
"mark.js": {
|
||||
"version": "8.11.1",
|
||||
"resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz",
|
||||
"integrity": "sha1-GA8fnr74sOY45BZq1S24eb6y/8U="
|
||||
},
|
||||
"marked": {
|
||||
"version": "0.3.18",
|
||||
"resolved": "https://registry.npmjs.org/marked/-/marked-0.3.18.tgz",
|
||||
"integrity": "sha512-49i2QYhfULqaXzNZpxC808PisuCTGT2fgG0zrzdCI9N3rIfAWfW0nggvbXr6zvpynZdOG5+9xNxdzP0kwZnERw=="
|
||||
},
|
||||
"memoize-one": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-4.0.0.tgz",
|
||||
"integrity": "sha512-wdpOJ4XBejprGn/xhd1i2XR8Dv1A25FJeIvR7syQhQlz9eXsv+06llcvcmBxlWVGv4C73QBsWA8kxvZozzNwiQ=="
|
||||
},
|
||||
"min-document": {
|
||||
"version": "2.19.0",
|
||||
"resolved": "https://registry.npmjs.org/min-document/-/min-document-2.19.0.tgz",
|
||||
"integrity": "sha1-e9KC4/WELtKVu3SM3Z8f+iyCRoU=",
|
||||
"requires": {
|
||||
"dom-walk": "^0.1.0"
|
||||
}
|
||||
},
|
||||
"mobx-react": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/mobx-react/-/mobx-react-5.2.3.tgz",
|
||||
"integrity": "sha512-OuSlF2nJEa1PGookZcZnINbvEK4iWNNYiqUh6aebk2AkWxj3sG8OafDOQMcMYApQALTHRsrBIjOx/K8TFxcz7w==",
|
||||
"requires": {
|
||||
"hoist-non-react-statics": "^2.5.0",
|
||||
"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="
|
||||
},
|
||||
"ono": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/ono/-/ono-4.0.2.tgz",
|
||||
"integrity": "sha512-EFXJFoeF+KkZW4lwmcPMKHp2ZU7o6CM+ccX2nPbEJKiJIdyqbIcS1v6pmNgeNJ6x4/vEYn0/8oz66qXSPnnmSQ==",
|
||||
"node-fetch": {
|
||||
"version": "1.7.3",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz",
|
||||
"integrity": "sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==",
|
||||
"requires": {
|
||||
"format-util": "1.0.3"
|
||||
"encoding": "^0.1.11",
|
||||
"is-stream": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
"integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
|
||||
},
|
||||
"ono": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/ono/-/ono-4.0.5.tgz",
|
||||
"integrity": "sha512-ZVNuV9kJbr/2tWs83I2snrYo+WIS0DISF/xUfX9p9b6GyDD6F5N9PzHjW+p/dep6IGwSYylf1HCub5I/nM0R5Q==",
|
||||
"requires": {
|
||||
"format-util": "^1.0.3"
|
||||
}
|
||||
},
|
||||
"openapi-sampler": {
|
||||
"version": "0.4.3",
|
||||
"resolved": "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-0.4.3.tgz",
|
||||
"integrity": "sha512-Ml6o1gt++ZQ4JKL344YRo/fX05yuM6C+l/mGVX2yjhu1BRKyrRK4Z46uBTKSVaag1xINBFwYG7dZdz/10AmPzA=="
|
||||
},
|
||||
"perfect-scrollbar": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/perfect-scrollbar/-/perfect-scrollbar-0.8.1.tgz",
|
||||
"integrity": "sha512-RNC5tX/JMRYR+qVdJTEAWnRxw0Yf9lvbO8lTuAOvgDODkiA8lveTSkvrNMhmaGKEyimJpJl+myb/syVS9YyPuw=="
|
||||
},
|
||||
"prismjs": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.9.0.tgz",
|
||||
"integrity": "sha1-+j4tntw8OIfB8fMJXUHx+bQgDw8=",
|
||||
"version": "1.0.0-beta.13",
|
||||
"resolved": "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.0.0-beta.13.tgz",
|
||||
"integrity": "sha512-NReKJh92NlUmY9CDo86L1Skkx3DMDeWmiLoqMxQSX7xBpoSx8WJ1JdTb7nEwz6M7S+WDPrQsEfS5BaIW27nMrQ==",
|
||||
"requires": {
|
||||
"clipboard": "1.7.1"
|
||||
"json-pointer": "^0.6.0"
|
||||
}
|
||||
},
|
||||
"process-nextick-args": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz",
|
||||
"integrity": "sha1-FQ4gt1ZZCtP5EJPyWk8q2L/zC6M="
|
||||
"perfect-scrollbar": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/perfect-scrollbar/-/perfect-scrollbar-1.4.0.tgz",
|
||||
"integrity": "sha512-/2Sk/khljhdrsamjJYS5NjrH+GKEHEwh7zFSiYyxROyYKagkE4kSn2zDQDRTOMo8mpT2jikxx6yI1dG7lNP/hw=="
|
||||
},
|
||||
"readable-stream": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.3.tgz",
|
||||
"integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==",
|
||||
"polished": {
|
||||
"version": "1.9.3",
|
||||
"resolved": "https://registry.npmjs.org/polished/-/polished-1.9.3.tgz",
|
||||
"integrity": "sha512-4NmSD7fMFlM8roNxs7YXPv7UFRbYzb0gufR5zBxJLRzY54+zFsavxBo6zsQzP9ep6Hh3pC2pTyrpSTBEaB6IkQ=="
|
||||
},
|
||||
"postcss-value-parser": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.0.tgz",
|
||||
"integrity": "sha1-h/OPnxj3dKSrTIojL1xc6IcqnRU="
|
||||
},
|
||||
"prismjs": {
|
||||
"version": "1.15.0",
|
||||
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.15.0.tgz",
|
||||
"integrity": "sha512-Lf2JrFYx8FanHrjoV5oL8YHCclLQgbJcVZR+gikGGMqz6ub5QVWDTM6YIwm3BuPxM/LOV+rKns3LssXNLIf+DA==",
|
||||
"requires": {
|
||||
"core-util-is": "1.0.2",
|
||||
"inherits": "2.0.3",
|
||||
"isarray": "1.0.0",
|
||||
"process-nextick-args": "1.0.7",
|
||||
"safe-buffer": "5.1.1",
|
||||
"string_decoder": "1.0.3",
|
||||
"util-deprecate": "1.0.2"
|
||||
"clipboard": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"process": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/process/-/process-0.5.2.tgz",
|
||||
"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": {
|
||||
"version": "15.6.2",
|
||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.2.tgz",
|
||||
"integrity": "sha512-3pboPvLiWD7dkI3qf3KbUe6hKFKa52w+AE0VCqECtf+QHAKgOL37tTaNCnuX1nAAQ4ZhyP+kYVKf8rLmJ/feDQ==",
|
||||
"requires": {
|
||||
"loose-envify": "^1.3.1",
|
||||
"object-assign": "^4.1.1"
|
||||
}
|
||||
},
|
||||
"react-dropdown": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dropdown/-/react-dropdown-1.5.0.tgz",
|
||||
"integrity": "sha512-rRv3a7NiP++yC1rzdjzkviC5ujq759i4SRa0M3C0Cr7loYT4Z3+JhSPekv1/04JiZNXX46cV3/g6A9kS7rkI4Q==",
|
||||
"requires": {
|
||||
"classnames": "^2.2.3"
|
||||
}
|
||||
},
|
||||
"react-hot-loader": {
|
||||
"version": "4.3.4",
|
||||
"resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.3.4.tgz",
|
||||
"integrity": "sha512-LlKjtHq+RhDq9xm6crXojbkzrEvli5F4/RaeJ//XtDWrwwsAHDjEqKfZZiPCxv7gWV2cxE3YE8TXeE9BDzLqOA==",
|
||||
"requires": {
|
||||
"fast-levenshtein": "^2.0.6",
|
||||
"global": "^4.3.0",
|
||||
"hoist-non-react-statics": "^2.5.0",
|
||||
"prop-types": "^15.6.1",
|
||||
"react-lifecycles-compat": "^3.0.4",
|
||||
"shallowequal": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"react-is": {
|
||||
"version": "16.4.2",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.4.2.tgz",
|
||||
"integrity": "sha512-rI3cGFj/obHbBz156PvErrS5xc6f1eWyTwyV4mo0vF2lGgXgS+mm7EKD5buLJq6jNgIagQescGSVG2YzgXt8Yg=="
|
||||
},
|
||||
"react-lifecycles-compat": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz",
|
||||
"integrity": "sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA=="
|
||||
},
|
||||
"react-tabs": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/react-tabs/-/react-tabs-2.2.2.tgz",
|
||||
"integrity": "sha512-jZGAAoq1yknr/XF60/2kH5X3UJdR1X8ItcsLZ1mJnHfoniKcCr3shT2TK5wiS2sO0LOmqwX2BtJQX3snKd50sg==",
|
||||
"requires": {
|
||||
"classnames": "^2.2.0",
|
||||
"prop-types": "^15.5.0"
|
||||
}
|
||||
},
|
||||
"redoc": {
|
||||
"version": "1.19.3",
|
||||
"resolved": "https://registry.npmjs.org/redoc/-/redoc-1.19.3.tgz",
|
||||
"integrity": "sha1-DfPx+6S92G/+nGIAEzBxUjytVec=",
|
||||
"version": "2.0.0-alpha.32",
|
||||
"resolved": "https://registry.npmjs.org/redoc/-/redoc-2.0.0-alpha.32.tgz",
|
||||
"integrity": "sha512-hqQlQ8lnXszLOJGyrRCLtCH+yPJfS22FjbqJ9X6/KM3U46UXk7rv3jZG/quV0IIRhcyehRm6h8a6Eu18KRupng==",
|
||||
"requires": {
|
||||
"core-js": "2.5.3",
|
||||
"dropkickjs": "2.1.10",
|
||||
"hint.css": "2.5.0",
|
||||
"https-browserify": "1.0.0",
|
||||
"json-pointer": "0.6.0",
|
||||
"json-schema-ref-parser": "3.3.1",
|
||||
"lunr": "1.0.0",
|
||||
"mark.js": "github:julmot/mark.js#714c9523feca999267f1758da8cfd92d077105d0",
|
||||
"openapi-sampler": "0.4.3",
|
||||
"perfect-scrollbar": "0.8.1",
|
||||
"prismjs": "1.9.0",
|
||||
"remarkable": "1.7.1",
|
||||
"scrollparent": "2.0.1",
|
||||
"slugify": "1.2.6",
|
||||
"stream-http": "2.7.2",
|
||||
"ts-helpers": "1.1.2",
|
||||
"zone.js": "0.8.18"
|
||||
},
|
||||
"dependencies": {
|
||||
"mark.js": {
|
||||
"version": "github:julmot/mark.js#714c9523feca999267f1758da8cfd92d077105d0"
|
||||
}
|
||||
"classnames": "^2.2.6",
|
||||
"decko": "^1.2.0",
|
||||
"dompurify": "^1.0.6",
|
||||
"eventemitter3": "^3.0.0",
|
||||
"json-pointer": "^0.6.0",
|
||||
"json-schema-ref-parser": "^5.1.1",
|
||||
"lunr": "^2.3.0",
|
||||
"mark.js": "^8.11.1",
|
||||
"marked": "0.3.18",
|
||||
"memoize-one": "^4.0.0",
|
||||
"mobx-react": "^5.2.3",
|
||||
"openapi-sampler": "1.0.0-beta.13",
|
||||
"perfect-scrollbar": "^1.4.0",
|
||||
"polished": "^1.9.3",
|
||||
"prismjs": "^1.15.0",
|
||||
"prop-types": "^15.6.2",
|
||||
"react-dropdown": "^1.3.0",
|
||||
"react-hot-loader": "^4.3.3",
|
||||
"react-tabs": "^2.0.0",
|
||||
"slugify": "^1.2.1",
|
||||
"stickyfill": "^1.1.1",
|
||||
"styled-components": "^3.3.3",
|
||||
"tslib": "^1.9.3"
|
||||
}
|
||||
},
|
||||
"remarkable": {
|
||||
"version": "1.7.1",
|
||||
"resolved": "https://registry.npmjs.org/remarkable/-/remarkable-1.7.1.tgz",
|
||||
"integrity": "sha1-qspJchALZqZCpjoQIcpLrBvjv/Y=",
|
||||
"requires": {
|
||||
"argparse": "0.1.16",
|
||||
"autolinker": "0.15.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"argparse": {
|
||||
"version": "0.1.16",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-0.1.16.tgz",
|
||||
"integrity": "sha1-z9AeD7uj1srtBJ+9dY1A9lGW9Xw=",
|
||||
"requires": {
|
||||
"underscore": "1.7.0",
|
||||
"underscore.string": "2.4.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"safe-buffer": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz",
|
||||
"integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg=="
|
||||
},
|
||||
"scrollparent": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/scrollparent/-/scrollparent-2.0.1.tgz",
|
||||
"integrity": "sha1-cV1bnMV3YPsivczDvvtb/gaxoxc="
|
||||
"safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||
},
|
||||
"select": {
|
||||
"version": "1.1.2",
|
||||
@@ -281,40 +441,69 @@
|
||||
"integrity": "sha1-DnNQrN7ICxEIUoeG7B1EGNEbOW0=",
|
||||
"optional": true
|
||||
},
|
||||
"setimmediate": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
|
||||
"integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU="
|
||||
},
|
||||
"shallowequal": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz",
|
||||
"integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ=="
|
||||
},
|
||||
"slugify": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.2.6.tgz",
|
||||
"integrity": "sha512-796YAGnzEnLKQHAFf7H2q1nsjY/9qywSnF9ZkMUbs9he4aZaXO/zFUow0LZ95sBAiQjOX1EmGl23gTYaswiNaQ=="
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.3.0.tgz",
|
||||
"integrity": "sha512-vvz+9ANt7CtdTHwJpfrsHOnGkgxky+CUPnvtzDZBZYFo/H/CdZkd5lJL7z7RqtH/x9QW/ItYYfHlcGf38CBK1w=="
|
||||
},
|
||||
"sprintf-js": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
|
||||
"integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw="
|
||||
},
|
||||
"stream-http": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.7.2.tgz",
|
||||
"integrity": "sha512-c0yTD2rbQzXtSsFSVhtpvY/vS6u066PcXOX9kBB3mSO76RiUQzL340uJkGBWnlBg4/HZzqiUXtaVA7wcRcJgEw==",
|
||||
"stickyfill": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/stickyfill/-/stickyfill-1.1.1.tgz",
|
||||
"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": {
|
||||
"builtin-status-codes": "3.0.0",
|
||||
"inherits": "2.0.3",
|
||||
"readable-stream": "2.3.3",
|
||||
"to-arraybuffer": "1.0.1",
|
||||
"xtend": "4.0.1"
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"string_decoder": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz",
|
||||
"integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==",
|
||||
"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": {
|
||||
"safe-buffer": "5.1.1"
|
||||
"has-flag": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"swagger-ui-dist": {
|
||||
"version": "3.8.1",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.8.1.tgz",
|
||||
"integrity": "sha1-jzVrkwjZl3oJ1eQYGvdCAHPtzdk="
|
||||
"version": "3.17.6",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.17.6.tgz",
|
||||
"integrity": "sha1-37Y7uHZdOKNzjPWUZYad4W3Uczk="
|
||||
},
|
||||
"tiny-emitter": {
|
||||
"version": "2.0.2",
|
||||
@@ -322,56 +511,20 @@
|
||||
"integrity": "sha512-2NM0auVBGft5tee/OxP4PI3d8WItkDM+fPnaRAVo6xTDI2knbz9eC5ArWGqtGlYqiH3RU5yMpdyTTO7MguC4ow==",
|
||||
"optional": true
|
||||
},
|
||||
"to-arraybuffer": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",
|
||||
"integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M="
|
||||
"tslib": {
|
||||
"version": "1.9.3",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz",
|
||||
"integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ=="
|
||||
},
|
||||
"ts-helpers": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/ts-helpers/-/ts-helpers-1.1.2.tgz",
|
||||
"integrity": "sha1-/Gm+nx87rtAfsaDvjUz+dIgU2DU="
|
||||
"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=="
|
||||
},
|
||||
"underscore": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.7.0.tgz",
|
||||
"integrity": "sha1-a7rwh3UA02vjTsqlhODbn+8DUgk="
|
||||
},
|
||||
"underscore.string": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-2.4.0.tgz",
|
||||
"integrity": "sha1-jN2PusTi0uoefi6Al8QvRCKA+Fs="
|
||||
},
|
||||
"util-deprecate": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
|
||||
},
|
||||
"validator": {
|
||||
"version": "9.2.0",
|
||||
"resolved": "https://registry.npmjs.org/validator/-/validator-9.2.0.tgz",
|
||||
"integrity": "sha512-6Ij4Eo0KM4LkR0d0IegOwluG5453uqT5QyF5SV5Ezvm8/zmkKI/L4eoraafZGlZPC9guLkwKzgypcw8VGWWnGA=="
|
||||
},
|
||||
"xtend": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz",
|
||||
"integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68="
|
||||
},
|
||||
"z-schema": {
|
||||
"version": "3.19.0",
|
||||
"resolved": "https://registry.npmjs.org/z-schema/-/z-schema-3.19.0.tgz",
|
||||
"integrity": "sha512-V94f3ODuluBS4kQLLjNhwoMek0dyIXCsvNu/A17dAyJ6sMhT5KkJQwSn07R0naByLIXJWMDk+ruMfI/3G3hS4Q==",
|
||||
"requires": {
|
||||
"commander": "2.12.2",
|
||||
"lodash.get": "4.4.2",
|
||||
"lodash.isequal": "4.5.0",
|
||||
"validator": "9.2.0"
|
||||
}
|
||||
},
|
||||
"zone.js": {
|
||||
"version": "0.8.18",
|
||||
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.8.18.tgz",
|
||||
"integrity": "sha512-knKOBQM0oea3/x9pdyDuDi7RhxDlJhOIkeixXSiTKWLgs4LpK37iBc+1HaHwzlciHUKT172CymJFKo8Xgh+44Q=="
|
||||
"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=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-3
@@ -1,7 +1,12 @@
|
||||
{
|
||||
"name": "drf-yasg",
|
||||
"dependencies": {
|
||||
"redoc": "^1.19.3",
|
||||
"swagger-ui-dist": "^3.8.1"
|
||||
}
|
||||
"redoc": "^2.0.0-alpha.32",
|
||||
"swagger-ui-dist": "^3.17.6"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/axnsan12/drf-yasg.git"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
.[validation]
|
||||
-r requirements/heroku.txt
|
||||
@@ -4,3 +4,8 @@ openapi_codec>=1.3.2
|
||||
ruamel.yaml>=0.15.34
|
||||
inflection>=0.3.1
|
||||
future>=0.16.0
|
||||
six>=1.10.0
|
||||
uritemplate>=3.0.0
|
||||
|
||||
djangorestframework>=3.7.7
|
||||
Django>=1.11.7
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
# requirements for CI test suite
|
||||
-r dev.txt
|
||||
# requirements for the CI test runner
|
||||
tox-travis>=0.10
|
||||
codecov>=2.0.9
|
||||
|
||||
-r tox.txt
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
# requirements for local development
|
||||
tox>=2.9.1
|
||||
# requirements for local development to be installed via pip install -r requirements/dev.txt
|
||||
-r tox.txt
|
||||
-r test.txt
|
||||
-r lint.txt
|
||||
|
||||
tox-battery>=0.5
|
||||
detox>=0.11
|
||||
|
||||
isort>=4.2
|
||||
flake8>=3.5.0
|
||||
flake8-isort>=2.3
|
||||
|
||||
-r setup.txt
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
Sphinx==1.6.5
|
||||
sphinx_rtd_theme==0.2.4
|
||||
Pillow==4.3.0
|
||||
readme_renderer==17.2
|
||||
# used by the 'docs' tox env for building the documentation
|
||||
Sphinx>=1.7.0
|
||||
sphinx_rtd_theme>=0.2.4
|
||||
Pillow>=4.3.0
|
||||
readme_renderer>=17.2
|
||||
|
||||
Django==2.0
|
||||
Django>=2.0,<2.1
|
||||
djangorestframework_camel_case>=0.2.0
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# requirements necessary when deploying the test project to heroku
|
||||
-r testproj.txt
|
||||
psycopg2>=2.7.3
|
||||
gunicorn>=19.7.1
|
||||
whitenoise>=3.3.1
|
||||
@@ -0,0 +1,4 @@
|
||||
# used by the 'lint' tox env for linting via flake8
|
||||
isort>=4.2
|
||||
flake8>=3.5.0
|
||||
flake8-isort>=2.3
|
||||
@@ -1,4 +1,4 @@
|
||||
# requirements for building the distributable package
|
||||
# needed to build the package setup_requires in setup.py
|
||||
|
||||
# do not unpin this (see setup.py)
|
||||
setuptools_scm==1.15.6
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# pytest runner + plugins
|
||||
# requirements for running the tests via pytest
|
||||
pytest>=2.9
|
||||
pytest-pythonpath>=0.7.1
|
||||
pytest-cov>=2.5.1
|
||||
# latest pip version of pytest-django is more than a year old and does not support Django 2.0
|
||||
git+https://github.com/pytest-dev/pytest-django.git@94cccb956435dd7a719606744ee7608397e1eafb
|
||||
pytest-xdist>=1.22.0
|
||||
pytest-django>=3.2.0
|
||||
datadiff==2.0.0
|
||||
|
||||
-r testproj.txt
|
||||
|
||||
@@ -5,3 +5,6 @@ django-cors-headers>=2.1.0
|
||||
django-filter>=1.1.0,<2.0; python_version == "2.7"
|
||||
django-filter>=1.1.0; python_version >= "3.4"
|
||||
djangorestframework-camel-case>=0.2.0
|
||||
djangorestframework-recursive>=0.1.2
|
||||
dj-database-url>=0.4.2
|
||||
user_agents>=1.1.0
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# requirements for building and running tox
|
||||
tox>=2.9.1,<3.0.0
|
||||
detox>=0.11
|
||||
|
||||
-r setup.txt
|
||||
@@ -0,0 +1 @@
|
||||
python-3.6.4
|
||||
@@ -0,0 +1,5 @@
|
||||
[bdist_wheel]
|
||||
universal = 1
|
||||
|
||||
[metadata]
|
||||
license_file = LICENSE.rst
|
||||
@@ -3,19 +3,21 @@
|
||||
import distutils.core
|
||||
import io
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import sys
|
||||
from setuptools import find_packages, setup
|
||||
|
||||
|
||||
def read_req(req_file):
|
||||
with open(os.path.join('requirements', req_file)) as req:
|
||||
return [line for line in req.readlines() if line and not line.isspace()]
|
||||
return [line.strip() for line in req.readlines() if line.strip() and not line.strip().startswith('#')]
|
||||
|
||||
|
||||
with io.open('README.rst', encoding='utf-8') as readme:
|
||||
description = readme.read()
|
||||
|
||||
requirements = ['djangorestframework>=3.7.0'] + read_req('base.txt')
|
||||
requirements = read_req('base.txt')
|
||||
requirements_setup = read_req('setup.txt')
|
||||
requirements_validation = read_req('validation.txt')
|
||||
|
||||
@@ -32,14 +34,14 @@ def _install_setup_requires(attrs):
|
||||
dist.fetch_build_eggs(dist.setup_requires)
|
||||
|
||||
|
||||
if 'sdist' in sys.argv:
|
||||
try:
|
||||
# try to install setuptools_scm before setuptools does it, otherwise our monkey patch below will come too early
|
||||
# (setuptools_scm adds find_files hooks into setuptools on install)
|
||||
_install_setup_requires({'setup_requires': requirements_setup})
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# try to install setuptools_scm before setuptools does it, otherwise our monkey patch below will come too early
|
||||
# (setuptools_scm adds find_files hooks into setuptools on install)
|
||||
_install_setup_requires({'setup_requires': requirements_setup})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if 'sdist' in sys.argv:
|
||||
try:
|
||||
# see https://github.com/pypa/setuptools_scm/issues/190, setuptools_scm includes ALL versioned files from
|
||||
# the git repo into the sdist by default, and there is no easy way to provide an opt-out;
|
||||
@@ -51,9 +53,22 @@ if 'sdist' in sys.argv:
|
||||
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
|
||||
|
||||
rnd = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
|
||||
version_kwargs = {'version': '0.0.0.dummy+' + rnd}
|
||||
|
||||
setup(
|
||||
name='drf-yasg',
|
||||
use_scm_version=True,
|
||||
packages=find_packages('src'),
|
||||
package_dir={'': 'src'},
|
||||
include_package_data=True,
|
||||
@@ -70,6 +85,7 @@ setup(
|
||||
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',
|
||||
@@ -89,4 +105,5 @@ setup(
|
||||
'Topic :: Documentation',
|
||||
'Topic :: Software Development :: Code Generators',
|
||||
],
|
||||
**version_kwargs
|
||||
)
|
||||
|
||||
@@ -2,15 +2,18 @@ from django.conf import settings
|
||||
from rest_framework.settings import perform_import
|
||||
|
||||
SWAGGER_DEFAULTS = {
|
||||
'DEFAULT_GENERATOR_CLASS': 'drf_yasg.generators.OpenAPISchemaGenerator',
|
||||
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.inspectors.SwaggerAutoSchema',
|
||||
|
||||
'DEFAULT_FIELD_INSPECTORS': [
|
||||
'drf_yasg.inspectors.CamelCaseJSONFilter',
|
||||
'drf_yasg.inspectors.RecursiveFieldInspector',
|
||||
'drf_yasg.inspectors.ReferencingSerializerInspector',
|
||||
'drf_yasg.inspectors.RelatedFieldInspector',
|
||||
'drf_yasg.inspectors.ChoiceFieldInspector',
|
||||
'drf_yasg.inspectors.FileFieldInspector',
|
||||
'drf_yasg.inspectors.DictFieldInspector',
|
||||
'drf_yasg.inspectors.HiddenFieldInspector',
|
||||
'drf_yasg.inspectors.RelatedFieldInspector',
|
||||
'drf_yasg.inspectors.SimpleFieldInspector',
|
||||
'drf_yasg.inspectors.StringDefaultFieldInspector',
|
||||
],
|
||||
@@ -23,7 +26,7 @@ SWAGGER_DEFAULTS = {
|
||||
],
|
||||
|
||||
'DEFAULT_INFO': None,
|
||||
'DEFAULT_API_URL': '',
|
||||
'DEFAULT_API_URL': None,
|
||||
|
||||
'USE_SESSION_AUTH': True,
|
||||
'SECURITY_DEFINITIONS': {
|
||||
@@ -31,6 +34,7 @@ SWAGGER_DEFAULTS = {
|
||||
'type': 'basic'
|
||||
}
|
||||
},
|
||||
'SECURITY_REQUIREMENTS': None,
|
||||
'LOGIN_URL': getattr(settings, 'LOGIN_URL', None),
|
||||
'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None),
|
||||
'VALIDATOR_URL': '',
|
||||
@@ -42,6 +46,19 @@ SWAGGER_DEFAULTS = {
|
||||
'SHOW_EXTENSIONS': True,
|
||||
'DEFAULT_MODEL_RENDERING': 'model',
|
||||
'DEFAULT_MODEL_DEPTH': 3,
|
||||
'SHOW_COMMON_EXTENSIONS': True,
|
||||
'OAUTH2_REDIRECT_URL': None,
|
||||
'OAUTH2_CONFIG': {},
|
||||
'SUPPORTED_SUBMIT_METHODS': [
|
||||
'get',
|
||||
'put',
|
||||
'post',
|
||||
'delete',
|
||||
'options',
|
||||
'head',
|
||||
'patch',
|
||||
'trace'
|
||||
],
|
||||
}
|
||||
|
||||
REDOC_DEFAULTS = {
|
||||
@@ -52,6 +69,7 @@ REDOC_DEFAULTS = {
|
||||
}
|
||||
|
||||
IMPORT_STRINGS = [
|
||||
'DEFAULT_GENERATOR_CLASS',
|
||||
'DEFAULT_AUTO_SCHEMA_CLASS',
|
||||
'DEFAULT_FIELD_INSPECTORS',
|
||||
'DEFAULT_FILTER_INSPECTORS',
|
||||
|
||||
+15
-9
@@ -5,29 +5,29 @@ import json
|
||||
from collections import OrderedDict
|
||||
|
||||
from coreapi.compat import force_bytes
|
||||
from django.utils.safestring import SafeData, SafeText
|
||||
from ruamel import yaml
|
||||
|
||||
from . import openapi
|
||||
from .app_settings import swagger_settings
|
||||
from .errors import SwaggerValidationError
|
||||
|
||||
|
||||
def _validate_flex(spec, codec):
|
||||
def _validate_flex(spec):
|
||||
from flex.core import parse as validate_flex
|
||||
from flex.exceptions import ValidationError
|
||||
try:
|
||||
validate_flex(spec)
|
||||
except ValidationError as ex:
|
||||
raise_from(SwaggerValidationError(str(ex), 'flex', spec, codec), ex)
|
||||
raise_from(SwaggerValidationError(str(ex)), ex)
|
||||
|
||||
|
||||
def _validate_swagger_spec_validator(spec, codec):
|
||||
def _validate_swagger_spec_validator(spec):
|
||||
from swagger_spec_validator.validator20 import validate_spec as validate_ssv
|
||||
from swagger_spec_validator.common import SwaggerValidationError as SSVErr
|
||||
try:
|
||||
validate_ssv(spec)
|
||||
except SSVErr as ex:
|
||||
raise_from(SwaggerValidationError(str(ex), 'swagger_spec_validator', spec, codec), ex)
|
||||
raise_from(SwaggerValidationError(str(ex)), ex)
|
||||
|
||||
|
||||
#:
|
||||
@@ -61,10 +61,17 @@ class _OpenAPICodec(object):
|
||||
raise TypeError('Expected a `openapi.Swagger` instance')
|
||||
|
||||
spec = self.generate_swagger_object(document)
|
||||
errors = {}
|
||||
for validator in self.validators:
|
||||
# validate a deepcopy of the spec to prevent the validator from messing with it
|
||||
# for example, swagger_spec_validator adds an x-scope property to all references
|
||||
VALIDATORS[validator](copy.deepcopy(spec), self)
|
||||
try:
|
||||
# validate a deepcopy of the spec to prevent the validator from messing with it
|
||||
# for example, swagger_spec_validator adds an x-scope property to all references
|
||||
VALIDATORS[validator](copy.deepcopy(spec))
|
||||
except SwaggerValidationError as e:
|
||||
errors[validator] = str(e)
|
||||
|
||||
if errors:
|
||||
raise SwaggerValidationError("spec validation failed", errors, spec, self)
|
||||
return force_bytes(self._dump_dict(spec))
|
||||
|
||||
def encode_error(self, err):
|
||||
@@ -87,7 +94,6 @@ class _OpenAPICodec(object):
|
||||
:return: swagger spec as dict
|
||||
:rtype: OrderedDict
|
||||
"""
|
||||
swagger.security_definitions = swagger_settings.SECURITY_DEFINITIONS
|
||||
return swagger.as_odict()
|
||||
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ class SwaggerError(Exception):
|
||||
|
||||
|
||||
class SwaggerValidationError(SwaggerError):
|
||||
def __init__(self, msg, validator_name, spec, source_codec, *args):
|
||||
def __init__(self, msg, errors=None, spec=None, source_codec=None, *args):
|
||||
super(SwaggerValidationError, self).__init__(msg, *args)
|
||||
self.validator_name = validator_name
|
||||
self.errors = errors
|
||||
self.spec = spec
|
||||
self.source_codec = source_codec
|
||||
|
||||
|
||||
+185
-55
@@ -1,25 +1,127 @@
|
||||
import copy
|
||||
import logging
|
||||
import re
|
||||
from collections import OrderedDict, defaultdict
|
||||
|
||||
import uritemplate
|
||||
from django.utils.encoding import force_text
|
||||
from coreapi.compat import urlparse
|
||||
from rest_framework import versioning
|
||||
from rest_framework.compat import URLPattern, URLResolver, get_original_route
|
||||
from rest_framework.schemas.generators import EndpointEnumerator as _EndpointEnumerator
|
||||
from rest_framework.schemas.generators import SchemaGenerator
|
||||
from rest_framework.schemas.generators import SchemaGenerator, endpoint_ordering
|
||||
from rest_framework.schemas.inspectors import get_pk_description
|
||||
from rest_framework.settings import api_settings as rest_framework_settings
|
||||
|
||||
from . import openapi
|
||||
from .app_settings import swagger_settings
|
||||
from .errors import SwaggerGenerationError
|
||||
from .inspectors.field import get_basic_type_info, get_queryset_field
|
||||
from .openapi import ReferenceResolver
|
||||
from .utils import force_real_str, get_consumes, get_produces
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PATH_PARAMETER_RE = re.compile(r'{(?P<parameter>\w+)}')
|
||||
|
||||
|
||||
class EndpointEnumerator(_EndpointEnumerator):
|
||||
def __init__(self, patterns=None, urlconf=None, request=None):
|
||||
super(EndpointEnumerator, self).__init__(patterns, urlconf)
|
||||
self.request = request
|
||||
|
||||
def get_path_from_regex(self, path_regex):
|
||||
if path_regex.endswith(')'):
|
||||
logger.warning("url pattern does not end in $ ('%s') - unexpected things might happen",
|
||||
path_regex)
|
||||
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):
|
||||
if not super(EndpointEnumerator, self).should_include_endpoint(path, callback):
|
||||
return False
|
||||
|
||||
version = getattr(self.request, 'version', None)
|
||||
versioning_class = getattr(callback.cls, 'versioning_class', None)
|
||||
if versioning_class is not None and issubclass(versioning_class, versioning.NamespaceVersioning):
|
||||
if version and version not in namespace.split(':'):
|
||||
return False
|
||||
|
||||
if getattr(callback.cls, 'swagger_schema', object()) is None:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def replace_version(self, path, callback):
|
||||
"""If ``request.version`` is not ``None`` and `callback` uses ``URLPathVersioning``, this function replaces
|
||||
the ``version`` parameter in `path` with the actual version.
|
||||
|
||||
:param str path: the templated path
|
||||
:param callback: the view callback
|
||||
:rtype: str
|
||||
"""
|
||||
versioning_class = getattr(callback.cls, 'versioning_class', None)
|
||||
if versioning_class is not None and issubclass(versioning_class, versioning.URLPathVersioning):
|
||||
version = getattr(self.request, 'version', None)
|
||||
if version:
|
||||
version_param = getattr(versioning_class, 'version_param', 'version')
|
||||
version_param = '{%s}' % version_param
|
||||
if version_param not in path:
|
||||
logger.info("view %s uses URLPathVersioning but URL %s has no param %s"
|
||||
% (callback.cls, path, version_param))
|
||||
path = path.replace(version_param, version)
|
||||
|
||||
return path
|
||||
|
||||
def get_api_endpoints(self, patterns=None, prefix='', app_name=None, namespace=None, ignored_endpoints=None):
|
||||
"""
|
||||
Return a list of all available API endpoints by inspecting the URL conf.
|
||||
|
||||
Copied entirely from super.
|
||||
"""
|
||||
if patterns is None:
|
||||
patterns = self.patterns
|
||||
|
||||
api_endpoints = []
|
||||
if ignored_endpoints is None:
|
||||
ignored_endpoints = set()
|
||||
|
||||
for pattern in patterns:
|
||||
path_regex = prefix + get_original_route(pattern)
|
||||
if isinstance(pattern, URLPattern):
|
||||
try:
|
||||
path = self.get_path_from_regex(path_regex)
|
||||
callback = pattern.callback
|
||||
url_name = pattern.name
|
||||
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
|
||||
path = self.replace_version(path, callback)
|
||||
|
||||
# avoid adding endpoints that have already been seen,
|
||||
# as Django resolves urls in top-down order
|
||||
if path in ignored_endpoints:
|
||||
continue
|
||||
ignored_endpoints.add(path)
|
||||
|
||||
for method in self.get_allowed_methods(callback):
|
||||
endpoint = (path, method, callback)
|
||||
api_endpoints.append(endpoint)
|
||||
except Exception: # pragma: no cover
|
||||
logger.warning('failed to enumerate view', exc_info=True)
|
||||
|
||||
elif isinstance(pattern, URLResolver):
|
||||
nested_endpoints = self.get_api_endpoints(
|
||||
patterns=pattern.url_patterns,
|
||||
prefix=path_regex,
|
||||
app_name="%s:%s" % (app_name, pattern.app_name) if app_name else pattern.app_name,
|
||||
namespace="%s:%s" % (namespace, pattern.namespace) if namespace else pattern.namespace,
|
||||
ignored_endpoints=ignored_endpoints
|
||||
)
|
||||
api_endpoints.extend(nested_endpoints)
|
||||
else:
|
||||
logger.warning("unknown pattern type {}".format(type(pattern)))
|
||||
|
||||
api_endpoints = sorted(api_endpoints, key=endpoint_ordering)
|
||||
|
||||
return api_endpoints
|
||||
|
||||
def unescape(self, s):
|
||||
"""Unescape all backslash escapes from `s`.
|
||||
|
||||
@@ -30,8 +132,8 @@ class EndpointEnumerator(_EndpointEnumerator):
|
||||
return re.sub(r'\\(.)', r'\1', s)
|
||||
|
||||
def unescape_path(self, path):
|
||||
"""Remove backslashes from all path components outside {parameters}. This is needed because
|
||||
Django>=2.0 ``path()``/``RoutePattern`` aggresively escapes all non-parameter path components.
|
||||
"""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
|
||||
|
||||
**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
|
||||
@@ -60,12 +162,19 @@ class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
endpoint_enumerator_class = EndpointEnumerator
|
||||
|
||||
def __init__(self, info, version='', url=swagger_settings.DEFAULT_API_URL, patterns=None, urlconf=None):
|
||||
def __init__(self, info, version='', url=None, patterns=None, urlconf=None):
|
||||
"""
|
||||
|
||||
:param .Info info: information about the API
|
||||
:param str version: API version string; can be omitted to use `info.default_version`
|
||||
:param str url: API url; can be empty to remove URL info from the result
|
||||
:param str version: API version string; if omitted, `info.default_version` will be used
|
||||
:param str url: API scheme, host and port; if ``None`` is passed and ``DEFAULT_API_URL`` is not set, the url
|
||||
will be inferred from the request made against the schema view, so you should generally not need to set
|
||||
this parameter explicitly; if the empty string is passed, no host and scheme will be emitted
|
||||
|
||||
If `url` is not ``None`` or the empty string, it must be a scheme-absolute uri (i.e. starting with http://
|
||||
or https://), and any path component is ignored;
|
||||
|
||||
See also: :ref:`documentation on base URL construction <custom-spec-base-url>`
|
||||
:param patterns: if given, only these patterns will be enumerated for inclusion in the API spec
|
||||
:param urlconf: if patterns is not given, use this urlconf to enumerate patterns;
|
||||
if not given, the default urlconf is used
|
||||
@@ -73,6 +182,18 @@ class OpenAPISchemaGenerator(object):
|
||||
self._gen = SchemaGenerator(info.title, url, info.get('description', ''), patterns, urlconf)
|
||||
self.info = info
|
||||
self.version = version
|
||||
self.consumes = []
|
||||
self.produces = []
|
||||
|
||||
if url is None and swagger_settings.DEFAULT_API_URL is not None:
|
||||
url = swagger_settings.DEFAULT_API_URL
|
||||
|
||||
if url:
|
||||
parsed_url = urlparse.urlparse(url)
|
||||
if parsed_url.scheme not in ('http', 'https') or not parsed_url.netloc:
|
||||
raise SwaggerGenerationError("`url` must be an absolute HTTP(S) url")
|
||||
if parsed_url.path:
|
||||
logger.warning("path component of api base URL %s is ignored; use FORCE_SCRIPT_NAME instead" % url)
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
@@ -89,17 +210,30 @@ class OpenAPISchemaGenerator(object):
|
||||
:rtype: openapi.Swagger
|
||||
"""
|
||||
endpoints = self.get_endpoints(request)
|
||||
endpoints = self.replace_version(endpoints, request)
|
||||
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
|
||||
paths = self.get_paths(endpoints, components, request, public)
|
||||
self.consumes = get_consumes(rest_framework_settings.DEFAULT_PARSER_CLASSES)
|
||||
self.produces = get_produces(rest_framework_settings.DEFAULT_RENDERER_CLASSES)
|
||||
paths, prefix = self.get_paths(endpoints, components, request, public)
|
||||
|
||||
security_definitions = swagger_settings.SECURITY_DEFINITIONS
|
||||
if security_definitions is not None:
|
||||
security_definitions = OrderedDict(sorted([(key, OrderedDict(sorted(sd.items())))
|
||||
for key, sd in swagger_settings.SECURITY_DEFINITIONS.items()]))
|
||||
security_requirements = swagger_settings.SECURITY_REQUIREMENTS
|
||||
if security_requirements is None:
|
||||
security_requirements = [{security_scheme: []} for security_scheme in swagger_settings.SECURITY_DEFINITIONS]
|
||||
|
||||
security_requirements = sorted(security_requirements, key=lambda od: list(sorted(od)))
|
||||
security_requirements = [OrderedDict(sorted(sr.items())) for sr in security_requirements]
|
||||
|
||||
url = self.url
|
||||
if not url and request is not None:
|
||||
if url is None and request is not None:
|
||||
url = request.build_absolute_uri()
|
||||
|
||||
return openapi.Swagger(
|
||||
info=self.info, paths=paths,
|
||||
_url=url, _version=self.version, **dict(components)
|
||||
info=self.info, paths=paths, consumes=self.consumes or None, produces=self.produces or None,
|
||||
security_definitions=security_definitions, security=security_requirements,
|
||||
_url=url, _prefix=prefix, _version=self.version, **dict(components)
|
||||
)
|
||||
|
||||
def create_view(self, callback, method, request=None):
|
||||
@@ -118,32 +252,10 @@ class OpenAPISchemaGenerator(object):
|
||||
view_method = getattr(view, method, None)
|
||||
if view_method is not None: # pragma: no cover
|
||||
setattr(view_method.__func__, '_swagger_auto_schema', overrides)
|
||||
|
||||
setattr(view, 'swagger_fake_view', True)
|
||||
return view
|
||||
|
||||
def replace_version(self, endpoints, request):
|
||||
"""If ``request.version`` is not ``None``, replace the version parameter in the path of any endpoints using
|
||||
``URLPathVersioning`` as a versioning class.
|
||||
|
||||
:param dict endpoints: endpoints as returned by :meth:`.get_endpoints`
|
||||
:param Request request: the request made against the schema view
|
||||
:return: endpoints with modified paths
|
||||
"""
|
||||
version = getattr(request, 'version', None)
|
||||
if version is None:
|
||||
return endpoints
|
||||
|
||||
new_endpoints = {}
|
||||
for path, endpoint in endpoints.items():
|
||||
view_cls = endpoint[0]
|
||||
versioning_class = getattr(view_cls, 'versioning_class', None)
|
||||
version_param = getattr(versioning_class, 'version_param', 'version')
|
||||
if versioning_class is not None and issubclass(versioning_class, versioning.URLPathVersioning):
|
||||
path = path.replace('{%s}' % version_param, version)
|
||||
|
||||
new_endpoints[path] = endpoint
|
||||
|
||||
return new_endpoints
|
||||
|
||||
def get_endpoints(self, request):
|
||||
"""Iterate over all the registered endpoints in the API and return a fake view with the right parameters.
|
||||
|
||||
@@ -151,7 +263,7 @@ class OpenAPISchemaGenerator(object):
|
||||
:return: {path: (view_class, list[(http_method, view_instance)])
|
||||
:rtype: dict
|
||||
"""
|
||||
enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf)
|
||||
enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf, request=request)
|
||||
endpoints = enumerator.get_api_endpoints()
|
||||
|
||||
view_paths = defaultdict(list)
|
||||
@@ -207,26 +319,35 @@ class OpenAPISchemaGenerator(object):
|
||||
:param ReferenceResolver components: resolver/container for Swagger References
|
||||
:param Request request: the request made against the schema view; can be None
|
||||
:param bool public: if True, all endpoints are included regardless of access through `request`
|
||||
:rtype: openapi.Paths
|
||||
:returns: the :class:`.Paths` object and the longest common path prefix, as a 2-tuple
|
||||
:rtype: tuple[openapi.Paths,str]
|
||||
"""
|
||||
if not endpoints:
|
||||
return openapi.Paths(paths={})
|
||||
return openapi.Paths(paths={}), ''
|
||||
|
||||
prefix = self.determine_path_prefix(list(endpoints.keys())) or ''
|
||||
assert '{' not in prefix, "base path cannot be templated in swagger 2.0"
|
||||
|
||||
prefix = self.determine_path_prefix(list(endpoints.keys()))
|
||||
paths = OrderedDict()
|
||||
|
||||
for path, (view_cls, methods) in sorted(endpoints.items()):
|
||||
operations = {}
|
||||
for method, view in methods:
|
||||
if not public and not self._gen.has_view_permissions(path, method, view):
|
||||
continue
|
||||
|
||||
operations[method.lower()] = self.get_operation(view, path, prefix, method, components, request)
|
||||
operation = self.get_operation(view, path, prefix, method, components, request)
|
||||
if operation is not None:
|
||||
operations[method.lower()] = operation
|
||||
|
||||
if operations:
|
||||
paths[path] = self.get_path_item(path, view_cls, operations)
|
||||
# since the common prefix is used as the API basePath, it must be stripped
|
||||
# from individual paths when writing them into the swagger document
|
||||
path_suffix = path[len(prefix):]
|
||||
if not path_suffix.startswith('/'):
|
||||
path_suffix = '/' + path_suffix
|
||||
paths[path_suffix] = self.get_path_item(path, view_cls, operations)
|
||||
|
||||
return openapi.Paths(paths=paths)
|
||||
return openapi.Paths(paths=paths), prefix
|
||||
|
||||
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
|
||||
@@ -241,7 +362,6 @@ class OpenAPISchemaGenerator(object):
|
||||
:param Request request: the request made against the schema view; can be None
|
||||
:rtype: openapi.Operation
|
||||
"""
|
||||
|
||||
operation_keys = self.get_operation_keys(path[len(prefix):], method, view)
|
||||
overrides = self.get_overrides(view, method)
|
||||
|
||||
@@ -253,8 +373,19 @@ class OpenAPISchemaGenerator(object):
|
||||
# 3. on the swagger_auto_schema decorator
|
||||
view_inspector_cls = overrides.get('auto_schema', view_inspector_cls)
|
||||
|
||||
if view_inspector_cls is None:
|
||||
return None
|
||||
|
||||
view_inspector = view_inspector_cls(view, path, method, components, request, overrides)
|
||||
return view_inspector.get_operation(operation_keys)
|
||||
operation = view_inspector.get_operation(operation_keys)
|
||||
if operation is None:
|
||||
return None
|
||||
|
||||
if 'consumes' in operation and set(operation.consumes) == set(self.consumes):
|
||||
del operation.consumes
|
||||
if 'produces' in operation and set(operation.produces) == set(self.produces):
|
||||
del operation.produces
|
||||
return operation
|
||||
|
||||
def get_path_item(self, path, view_cls, operations):
|
||||
"""Get a :class:`.PathItem` object that describes the parameters and operations related to a single path in the
|
||||
@@ -283,7 +414,7 @@ class OpenAPISchemaGenerator(object):
|
||||
if method in overrides:
|
||||
overrides = overrides[method]
|
||||
|
||||
return overrides
|
||||
return copy.deepcopy(overrides)
|
||||
|
||||
def get_path_parameters(self, path, view_cls):
|
||||
"""Return a list of Parameter instances corresponding to any templated path variables.
|
||||
@@ -295,24 +426,23 @@ class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
parameters = []
|
||||
queryset = getattr(view_cls, 'queryset', None)
|
||||
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
|
||||
|
||||
for variable in uritemplate.variables(path):
|
||||
for variable in sorted(uritemplate.variables(path)):
|
||||
model, model_field = get_queryset_field(queryset, variable)
|
||||
attrs = get_basic_type_info(model_field) or {'type': openapi.TYPE_STRING}
|
||||
if hasattr(view_cls, 'lookup_value_regex') and getattr(view_cls, 'lookup_field', None) == variable:
|
||||
attrs['pattern'] = view_cls.lookup_value_regex
|
||||
if getattr(view_cls, 'lookup_field', None) == variable and attrs['type'] == openapi.TYPE_STRING:
|
||||
attrs['pattern'] = getattr(view_cls, 'lookup_value_regex', attrs.get('pattern', None))
|
||||
|
||||
if model_field and model_field.help_text:
|
||||
description = force_text(model_field.help_text)
|
||||
elif model_field and model_field.primary_key:
|
||||
if model_field and getattr(model_field, 'help_text', False):
|
||||
description = model_field.help_text
|
||||
elif model_field and getattr(model_field, 'primary_key', False):
|
||||
description = get_pk_description(model, model_field)
|
||||
else:
|
||||
description = None
|
||||
|
||||
field = openapi.Parameter(
|
||||
name=variable,
|
||||
description=description,
|
||||
description=force_real_str(description),
|
||||
required=True,
|
||||
in_=openapi.IN_PATH,
|
||||
**attrs
|
||||
|
||||
@@ -3,8 +3,9 @@ from .base import (
|
||||
BaseInspector, FieldInspector, FilterInspector, NotHandled, PaginatorInspector, SerializerInspector, ViewInspector
|
||||
)
|
||||
from .field import (
|
||||
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, InlineSerializerInspector,
|
||||
ReferencingSerializerInspector, RelatedFieldInspector, SimpleFieldInspector, StringDefaultFieldInspector
|
||||
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, HiddenFieldInspector,
|
||||
InlineSerializerInspector, RecursiveFieldInspector, ReferencingSerializerInspector, RelatedFieldInspector,
|
||||
SimpleFieldInspector, StringDefaultFieldInspector
|
||||
)
|
||||
from .query import CoreAPICompatInspector, DjangoRestResponsePagination
|
||||
from .view import SwaggerAutoSchema
|
||||
@@ -22,9 +23,9 @@ __all__ = [
|
||||
'CoreAPICompatInspector', 'DjangoRestResponsePagination',
|
||||
|
||||
# field inspectors
|
||||
'InlineSerializerInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector', 'SimpleFieldInspector',
|
||||
'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector', 'StringDefaultFieldInspector',
|
||||
'CamelCaseJSONFilter',
|
||||
'InlineSerializerInspector', 'RecursiveFieldInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector',
|
||||
'SimpleFieldInspector', 'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector',
|
||||
'StringDefaultFieldInspector', 'CamelCaseJSONFilter', 'HiddenFieldInspector',
|
||||
|
||||
# view inspectors
|
||||
'SwaggerAutoSchema',
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import inspect
|
||||
import logging
|
||||
|
||||
from django.utils.encoding import force_text
|
||||
from rest_framework import serializers
|
||||
from rest_framework.utils import encoders, json
|
||||
|
||||
from .. import openapi
|
||||
from ..utils import is_list_view
|
||||
from ..utils import decimal_as_float, force_real_str, is_list_view
|
||||
|
||||
#: Sentinel value that inspectors must return to signal that they do not know how to handle an object
|
||||
NotHandled = object()
|
||||
@@ -196,9 +195,9 @@ class FieldInspector(BaseInspector):
|
||||
"""
|
||||
assert swagger_object_type in (openapi.Schema, openapi.Parameter, openapi.Items)
|
||||
assert not isinstance(field, openapi.SwaggerDict), "passed field is already a SwaggerDict object"
|
||||
title = force_text(field.label) if field.label else None
|
||||
title = force_real_str(field.label) if field.label else None
|
||||
title = title if swagger_object_type == openapi.Schema else None # only Schema has title
|
||||
description = force_text(field.help_text) if field.help_text else None
|
||||
description = force_real_str(field.help_text) if field.help_text else None
|
||||
description = description if swagger_object_type != openapi.Items else None # Items has no description either
|
||||
|
||||
def SwaggerType(existing_object=None, **instance_kwargs):
|
||||
@@ -224,6 +223,8 @@ class FieldInspector(BaseInspector):
|
||||
# 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)
|
||||
@@ -232,7 +233,8 @@ class FieldInspector(BaseInspector):
|
||||
if default is not None:
|
||||
instance_kwargs['default'] = default
|
||||
|
||||
instance_kwargs.setdefault('title', title)
|
||||
if instance_kwargs.get('type', None) != openapi.TYPE_ARRAY:
|
||||
instance_kwargs.setdefault('title', title)
|
||||
instance_kwargs.setdefault('description', description)
|
||||
instance_kwargs.update(kwargs)
|
||||
|
||||
@@ -273,7 +275,10 @@ class SerializerInspector(FieldInspector):
|
||||
|
||||
|
||||
class ViewInspector(BaseInspector):
|
||||
body_methods = ('PUT', 'PATCH', 'POST') #: methods that are allowed to have a request body
|
||||
body_methods = ('PUT', 'PATCH', 'POST', 'DELETE') #: methods that are allowed to have a request body
|
||||
|
||||
#: methods that are assumed to require a request body determined by the view's ``serializer_class``
|
||||
implicit_body_methods = ('PUT', 'PATCH', 'POST')
|
||||
|
||||
# real values set in __init__ to prevent import errors
|
||||
field_inspectors = [] #:
|
||||
@@ -365,7 +370,7 @@ class ViewInspector(BaseInspector):
|
||||
|
||||
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
|
||||
:returns: the converted :class:`.Schema`, or ``None`` in case of an unknown serializer
|
||||
:rtype: openapi.Schema,openapi.SchemaRef,None
|
||||
:rtype: openapi.Schema,openapi.SchemaRef
|
||||
"""
|
||||
return self.probe_inspectors(
|
||||
self.field_inspectors, 'get_schema', serializer, {'field_inspectors': self.field_inspectors}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import logging
|
||||
import operator
|
||||
from collections import OrderedDict
|
||||
from decimal import Decimal
|
||||
|
||||
from django.core import validators
|
||||
from django.db import models
|
||||
@@ -8,9 +10,11 @@ from rest_framework.settings import api_settings as rest_framework_settings
|
||||
|
||||
from .. import openapi
|
||||
from ..errors import SwaggerGenerationError
|
||||
from ..utils import filter_none
|
||||
from ..utils import decimal_as_float, filter_none, get_serializer_ref_name
|
||||
from .base import FieldInspector, NotHandled, SerializerInspector
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class InlineSerializerInspector(SerializerInspector):
|
||||
"""Provides serializer conversions using :meth:`.FieldInspector.field_to_swagger_object`."""
|
||||
@@ -18,12 +22,36 @@ class InlineSerializerInspector(SerializerInspector):
|
||||
#: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section
|
||||
use_definitions = False
|
||||
|
||||
def add_manual_fields(self, serializer, schema):
|
||||
"""Set fields from the ``swagger_schem_fields`` attribute on the serializer's Meta class. This method is called
|
||||
only for serializers that are converted into ``openapi.Schema`` objects.
|
||||
|
||||
:param serializer: serializer instance
|
||||
:param openapi.Schema schema: the schema object to be modified in-place
|
||||
"""
|
||||
serializer_meta = getattr(serializer, 'Meta', None)
|
||||
swagger_schema_fields = getattr(serializer_meta, 'swagger_schema_fields', {})
|
||||
if swagger_schema_fields:
|
||||
for attr, val in swagger_schema_fields.items():
|
||||
setattr(schema, attr, val)
|
||||
|
||||
def get_schema(self, serializer):
|
||||
return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions)
|
||||
|
||||
def add_manual_parameters(self, serializer, parameters):
|
||||
"""Add/replace parameters from the given list of automatically generated request parameters. This method
|
||||
is called only when the serializer is converted into a list of parameters for use in a form data request.
|
||||
|
||||
:param serializer: serializer instance
|
||||
:param list[openapi.Parameter] parameters: genereated parameters
|
||||
:return: modified parameters
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
return parameters
|
||||
|
||||
def get_request_parameters(self, serializer, in_):
|
||||
fields = getattr(serializer, 'fields', {})
|
||||
return [
|
||||
parameters = [
|
||||
self.probe_field_inspectors(
|
||||
value, openapi.Parameter, self.use_definitions,
|
||||
name=self.get_parameter_name(key), in_=in_
|
||||
@@ -32,12 +60,17 @@ class InlineSerializerInspector(SerializerInspector):
|
||||
in fields.items()
|
||||
]
|
||||
|
||||
return self.add_manual_parameters(serializer, parameters)
|
||||
|
||||
def get_property_name(self, field_name):
|
||||
return field_name
|
||||
|
||||
def get_parameter_name(self, field_name):
|
||||
return field_name
|
||||
|
||||
def get_serializer_ref_name(self, serializer):
|
||||
return get_serializer_ref_name(serializer)
|
||||
|
||||
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
|
||||
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
|
||||
|
||||
@@ -51,36 +84,41 @@ class InlineSerializerInspector(SerializerInspector):
|
||||
if swagger_object_type != openapi.Schema:
|
||||
raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__)
|
||||
|
||||
serializer = field
|
||||
serializer_meta = getattr(serializer, 'Meta', None)
|
||||
if hasattr(serializer_meta, 'ref_name'):
|
||||
ref_name = serializer_meta.ref_name
|
||||
else:
|
||||
ref_name = type(serializer).__name__
|
||||
if ref_name.endswith('Serializer'):
|
||||
ref_name = ref_name[:-len('Serializer')]
|
||||
ref_name = self.get_serializer_ref_name(field)
|
||||
|
||||
def make_schema_definition():
|
||||
properties = OrderedDict()
|
||||
required = []
|
||||
for property_name, child in serializer.fields.items():
|
||||
for property_name, child in field.fields.items():
|
||||
property_name = self.get_property_name(property_name)
|
||||
prop_kwargs = {
|
||||
'read_only': child.read_only or None
|
||||
'read_only': bool(child.read_only) or None
|
||||
}
|
||||
prop_kwargs = filter_none(prop_kwargs)
|
||||
|
||||
properties[property_name] = self.probe_field_inspectors(
|
||||
child_schema = self.probe_field_inspectors(
|
||||
child, ChildSwaggerType, use_references, **prop_kwargs
|
||||
)
|
||||
if child.required:
|
||||
properties[property_name] = child_schema
|
||||
|
||||
if child.required and not getattr(child_schema, 'read_only', False):
|
||||
required.append(property_name)
|
||||
|
||||
return SwaggerType(
|
||||
result = SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties=properties,
|
||||
required=required or None,
|
||||
)
|
||||
if not ref_name and 'title' in result:
|
||||
# on an inline model, the title is derived from the field name
|
||||
# but is visually displayed like the model name, which is confusing
|
||||
# it is better to just remove title from inline models
|
||||
del result.title
|
||||
|
||||
# Provide an option to add manual paremeters to a schema
|
||||
# for example, to add examples
|
||||
self.add_manual_fields(field, result)
|
||||
return result
|
||||
|
||||
if not ref_name or not use_references:
|
||||
return make_schema_definition()
|
||||
@@ -147,7 +185,11 @@ def get_related_model(model, source):
|
||||
:return: related model or ``None``
|
||||
"""
|
||||
try:
|
||||
return getattr(model, source).rel.related_model
|
||||
descriptor = getattr(model, source)
|
||||
try:
|
||||
return descriptor.rel.related_model
|
||||
except Exception:
|
||||
return descriptor.field.remote_field.model
|
||||
except Exception: # pragma: no cover
|
||||
return None
|
||||
|
||||
@@ -258,18 +300,33 @@ def find_limits(field):
|
||||
if isinstance(field, field_class)
|
||||
]
|
||||
|
||||
if isinstance(field, serializers.DecimalField) and not decimal_as_float(field):
|
||||
return limits
|
||||
|
||||
for validator in field.validators:
|
||||
if not hasattr(validator, 'limit_value'):
|
||||
continue
|
||||
|
||||
limit_value = validator.limit_value
|
||||
if isinstance(limit_value, Decimal) and decimal_as_float(field):
|
||||
limit_value = float(limit_value)
|
||||
|
||||
for validator_class, attr, improves in applicable_limits:
|
||||
if isinstance(validator, validator_class):
|
||||
if attr not in limits or improves(validator.limit_value, limits[attr]):
|
||||
limits[attr] = validator.limit_value
|
||||
if attr not in limits or improves(limit_value, limits[attr]):
|
||||
limits[attr] = limit_value
|
||||
|
||||
if hasattr(field, "allow_blank") and not field.allow_blank:
|
||||
if limits.get('min_length', 0) < 1:
|
||||
limits['min_length'] = 1
|
||||
|
||||
return OrderedDict(sorted(limits.items()))
|
||||
|
||||
|
||||
def decimal_field_type(field):
|
||||
return openapi.TYPE_NUMBER if decimal_as_float(field) else openapi.TYPE_STRING
|
||||
|
||||
|
||||
model_field_to_basic_type = [
|
||||
(models.AutoField, (openapi.TYPE_INTEGER, None)),
|
||||
(models.BinaryField, (openapi.TYPE_STRING, openapi.FORMAT_BINARY)),
|
||||
@@ -277,7 +334,7 @@ model_field_to_basic_type = [
|
||||
(models.NullBooleanField, (openapi.TYPE_BOOLEAN, None)),
|
||||
(models.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
|
||||
(models.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
|
||||
(models.DecimalField, (openapi.TYPE_NUMBER, None)),
|
||||
(models.DecimalField, (decimal_field_type, openapi.FORMAT_DECIMAL)),
|
||||
(models.DurationField, (openapi.TYPE_INTEGER, None)),
|
||||
(models.FloatField, (openapi.TYPE_NUMBER, None)),
|
||||
(models.IntegerField, (openapi.TYPE_INTEGER, None)),
|
||||
@@ -300,9 +357,11 @@ serializer_field_to_basic_type = [
|
||||
(serializers.UUIDField, (openapi.TYPE_STRING, openapi.FORMAT_UUID)),
|
||||
(serializers.RegexField, (openapi.TYPE_STRING, None)),
|
||||
(serializers.CharField, (openapi.TYPE_STRING, None)),
|
||||
((serializers.BooleanField, serializers.NullBooleanField), (openapi.TYPE_BOOLEAN, None)),
|
||||
(serializers.BooleanField, (openapi.TYPE_BOOLEAN, None)),
|
||||
(serializers.NullBooleanField, (openapi.TYPE_BOOLEAN, None)),
|
||||
(serializers.IntegerField, (openapi.TYPE_INTEGER, None)),
|
||||
((serializers.FloatField, serializers.DecimalField), (openapi.TYPE_NUMBER, None)),
|
||||
(serializers.FloatField, (openapi.TYPE_NUMBER, None)),
|
||||
(serializers.DecimalField, (decimal_field_type, openapi.FORMAT_DECIMAL)),
|
||||
(serializers.DurationField, (openapi.TYPE_NUMBER, None)), # ?
|
||||
(serializers.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
|
||||
(serializers.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
|
||||
@@ -326,13 +385,18 @@ def get_basic_type_info(field):
|
||||
for field_class, type_format in basic_type_info:
|
||||
if isinstance(field, field_class):
|
||||
swagger_type, format = type_format
|
||||
if callable(swagger_type):
|
||||
swagger_type = swagger_type(field)
|
||||
if callable(format):
|
||||
format = format(field)
|
||||
break
|
||||
else: # pragma: no cover
|
||||
return None
|
||||
|
||||
pattern = find_regex(field) if format in (None, openapi.FORMAT_SLUG) else None
|
||||
pattern = None
|
||||
if swagger_type == openapi.TYPE_STRING and format in (None, openapi.FORMAT_SLUG):
|
||||
pattern = find_regex(field)
|
||||
|
||||
limits = find_limits(field)
|
||||
|
||||
result = OrderedDict([
|
||||
@@ -365,16 +429,29 @@ class ChoiceFieldInspector(FieldInspector):
|
||||
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)
|
||||
|
||||
if isinstance(field, serializers.MultipleChoiceField):
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=ChildSwaggerType(
|
||||
type=openapi.TYPE_STRING,
|
||||
enum=list(field.choices.keys())
|
||||
if isinstance(field, serializers.ChoiceField):
|
||||
enum_type = openapi.TYPE_STRING
|
||||
|
||||
# for ModelSerializer, try to infer the type from the associated model field
|
||||
serializer = get_parent_serializer(field)
|
||||
if isinstance(serializer, serializers.ModelSerializer):
|
||||
model = getattr(getattr(serializer, 'Meta'), 'model')
|
||||
model_field = get_model_field(model, field.source)
|
||||
if model_field:
|
||||
model_type = get_basic_type_info(model_field)
|
||||
if model_type:
|
||||
enum_type = model_type.get('type', enum_type)
|
||||
|
||||
if isinstance(field, serializers.MultipleChoiceField):
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=ChildSwaggerType(
|
||||
type=enum_type,
|
||||
enum=list(field.choices.keys())
|
||||
)
|
||||
)
|
||||
)
|
||||
elif isinstance(field, serializers.ChoiceField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, enum=list(field.choices.keys()))
|
||||
|
||||
return SwaggerType(type=enum_type, enum=list(field.choices.keys()))
|
||||
|
||||
return NotHandled
|
||||
|
||||
@@ -422,11 +499,21 @@ class DictFieldInspector(FieldInspector):
|
||||
return NotHandled
|
||||
|
||||
|
||||
class HiddenFieldInspector(FieldInspector):
|
||||
"""Hide ``HiddenField``."""
|
||||
|
||||
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
|
||||
if isinstance(field, serializers.HiddenField):
|
||||
return None
|
||||
|
||||
return NotHandled
|
||||
|
||||
|
||||
class StringDefaultFieldInspector(FieldInspector):
|
||||
"""For otherwise unhandled fields, return them as plain :data:`.TYPE_STRING` objects."""
|
||||
|
||||
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs): # pragma: no cover
|
||||
# TODO unhandled fields: TimeField HiddenField JSONField
|
||||
# TODO unhandled fields: TimeField JSONField
|
||||
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
|
||||
@@ -462,11 +549,34 @@ else:
|
||||
"""Converts property names to camelCase if ``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer`` are used."""
|
||||
|
||||
def is_camel_case(self):
|
||||
return any(issubclass(parser, CamelCaseJSONParser) for parser in self.view.parser_classes) \
|
||||
or any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.view.renderer_classes)
|
||||
return (
|
||||
any(issubclass(parser, CamelCaseJSONParser) for parser in self.view.parser_classes) or
|
||||
any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.view.renderer_classes)
|
||||
)
|
||||
|
||||
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:
|
||||
from rest_framework_recursive.fields import RecursiveField
|
||||
except ImportError: # pragma: no cover
|
||||
class RecursiveFieldInspector(FieldInspector):
|
||||
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
|
||||
pass
|
||||
else:
|
||||
class RecursiveFieldInspector(FieldInspector):
|
||||
"""Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)"""
|
||||
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
|
||||
if isinstance(field, RecursiveField) and swagger_object_type == openapi.Schema:
|
||||
assert use_references is True, "Can not create schema for RecursiveField when use_references is False"
|
||||
|
||||
ref_name = get_serializer_ref_name(field.proxied)
|
||||
assert ref_name is not None, "Can not create RecursiveField schema for inline ModelSerializer"
|
||||
|
||||
return openapi.SchemaRef(self.components.with_scope(openapi.SCHEMA_DEFINITIONS), ref_name,
|
||||
ignore_unresolved=True)
|
||||
|
||||
return NotHandled
|
||||
|
||||
@@ -3,6 +3,8 @@ from collections import OrderedDict
|
||||
import coreschema
|
||||
from rest_framework.pagination import CursorPagination, LimitOffsetPagination, PageNumberPagination
|
||||
|
||||
from drf_yasg.utils import force_real_str
|
||||
|
||||
from .. import openapi
|
||||
from .base import FilterInspector, PaginatorInspector
|
||||
|
||||
@@ -48,7 +50,7 @@ class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
|
||||
in_=location_to_in[field.location],
|
||||
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
|
||||
required=field.required,
|
||||
description=field.schema.description,
|
||||
description=force_real_str(field.schema.description) if field.schema else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -70,7 +72,10 @@ class DjangoRestResponsePagination(PaginatorInspector):
|
||||
('previous', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)),
|
||||
('results', response_schema),
|
||||
)),
|
||||
required=['count', 'results']
|
||||
required=['results']
|
||||
)
|
||||
|
||||
if has_count:
|
||||
paged_schema.required.insert(0, 'count')
|
||||
|
||||
return paged_schema
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
from collections import OrderedDict
|
||||
|
||||
from rest_framework.request import is_form_media_type
|
||||
@@ -6,9 +7,14 @@ from rest_framework.status import is_success
|
||||
|
||||
from .. import openapi
|
||||
from ..errors import SwaggerGenerationError
|
||||
from ..utils import force_serializer_instance, guess_response_status, is_list_view, no_body, param_list_to_odict
|
||||
from ..utils import (
|
||||
force_real_str, force_serializer_instance, get_consumes, get_produces, guess_response_status, is_list_view, no_body,
|
||||
param_list_to_odict
|
||||
)
|
||||
from .base import ViewInspector
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SwaggerAutoSchema(ViewInspector):
|
||||
def __init__(self, view, path, method, components, request, overrides):
|
||||
@@ -18,6 +24,7 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
|
||||
def get_operation(self, operation_keys):
|
||||
consumes = self.get_consumes()
|
||||
produces = self.get_produces()
|
||||
|
||||
body = self.get_request_body_parameters(consumes)
|
||||
query = self.get_query_parameters()
|
||||
@@ -27,17 +34,21 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
|
||||
operation_id = self.get_operation_id(operation_keys)
|
||||
description = self.get_description()
|
||||
security = self.get_security()
|
||||
assert security is None or isinstance(security, list), "security must be a list of securiy requirement objects"
|
||||
tags = self.get_tags(operation_keys)
|
||||
|
||||
responses = self.get_responses()
|
||||
|
||||
return openapi.Operation(
|
||||
operation_id=operation_id,
|
||||
description=description,
|
||||
description=force_real_str(description),
|
||||
responses=responses,
|
||||
parameters=parameters,
|
||||
consumes=consumes,
|
||||
produces=produces,
|
||||
tags=tags,
|
||||
security=security
|
||||
)
|
||||
|
||||
def get_request_body_parameters(self, consumes):
|
||||
@@ -75,12 +86,17 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
"""
|
||||
if not hasattr(self.view, 'get_serializer'):
|
||||
return None
|
||||
return self.view.get_serializer()
|
||||
try:
|
||||
return self.view.get_serializer()
|
||||
except Exception:
|
||||
log.warning("view's get_serializer raised exception (%s %s %s)",
|
||||
self.method, self.path, type(self.view).__name__, exc_info=True)
|
||||
return None
|
||||
|
||||
def get_request_serializer(self):
|
||||
"""Return the request serializer (used for parsing the request payload) for this endpoint.
|
||||
def _get_request_body_override(self):
|
||||
"""Parse the request_body key in the override dict. This method is not public API.
|
||||
|
||||
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
|
||||
:return:
|
||||
"""
|
||||
body_override = self.overrides.get('request_body', None)
|
||||
|
||||
@@ -88,15 +104,25 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
if body_override is no_body:
|
||||
return None
|
||||
if self.method not in self.body_methods:
|
||||
raise SwaggerGenerationError("request_body can only be applied to PUT, PATCH or POST views; "
|
||||
"are you looking for query_serializer or manual_parameters?")
|
||||
raise SwaggerGenerationError("request_body can only be applied to (" + ','.join(self.body_methods) +
|
||||
"); are you looking for query_serializer or manual_parameters?")
|
||||
if isinstance(body_override, openapi.Schema.OR_REF):
|
||||
return body_override
|
||||
return force_serializer_instance(body_override)
|
||||
elif self.method in self.body_methods:
|
||||
|
||||
return body_override
|
||||
|
||||
def get_request_serializer(self):
|
||||
"""Return the request serializer (used for parsing the request payload) for this endpoint.
|
||||
|
||||
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
|
||||
"""
|
||||
body_override = self._get_request_body_override()
|
||||
|
||||
if body_override is None and self.method in self.implicit_body_methods:
|
||||
return self.get_view_serializer()
|
||||
|
||||
return None
|
||||
return body_override
|
||||
|
||||
def get_request_form_parameters(self, serializer):
|
||||
"""Given a Serializer, return a list of ``in: formData`` :class:`.Parameter`\ s.
|
||||
@@ -136,8 +162,11 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body")
|
||||
if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover
|
||||
if any(param.in_ == openapi.IN_BODY for param in parameters.values()):
|
||||
raise SwaggerGenerationError("cannot add form parameters when the request has a request schema; "
|
||||
raise SwaggerGenerationError("cannot add form parameters when the request has a request body; "
|
||||
"did you forget to set an appropriate parser class on the view?")
|
||||
if self.method not in self.body_methods:
|
||||
raise SwaggerGenerationError("form parameters can only be applied to (" + ','.join(self.body_methods) +
|
||||
") HTTP methods")
|
||||
|
||||
parameters.update(param_list_to_odict(manual_parameters))
|
||||
return list(parameters.values())
|
||||
@@ -153,6 +182,14 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
responses=self.get_response_schemas(response_serializers)
|
||||
)
|
||||
|
||||
def get_default_response_serializer(self):
|
||||
"""Return the default response serializer for this endpoint. This is derived from either the ``request_body``
|
||||
override or the request serializer (:meth:`.get_view_serializer`).
|
||||
|
||||
:return: response serializer, :class:`.Schema`, :class:`.SchemaRef`, ``None``
|
||||
"""
|
||||
return self._get_request_body_override() or self.get_view_serializer()
|
||||
|
||||
def get_default_responses(self):
|
||||
"""Get the default responses determined for this view from the request serializer and request method.
|
||||
|
||||
@@ -163,7 +200,7 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
default_status = guess_response_status(method)
|
||||
default_schema = ''
|
||||
if method in ('get', 'post', 'put', 'patch'):
|
||||
default_schema = self.get_request_serializer() or self.get_view_serializer()
|
||||
default_schema = self.get_default_response_serializer()
|
||||
|
||||
default_schema = default_schema or ''
|
||||
if any(is_form_media_type(encoding) for encoding in self.get_consumes()):
|
||||
@@ -209,11 +246,13 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
for sc, serializer in response_serializers.items():
|
||||
if isinstance(serializer, str):
|
||||
response = openapi.Response(
|
||||
description=serializer
|
||||
description=force_real_str(serializer)
|
||||
)
|
||||
elif not serializer:
|
||||
continue
|
||||
elif isinstance(serializer, openapi.Response):
|
||||
response = serializer
|
||||
if not isinstance(response.schema, openapi.Schema.OR_REF):
|
||||
if hasattr(response, 'schema') and not isinstance(response.schema, openapi.Schema.OR_REF):
|
||||
serializer = force_serializer_instance(response.schema)
|
||||
response.schema = self.serializer_to_schema(serializer)
|
||||
elif isinstance(serializer, openapi.Schema.OR_REF):
|
||||
@@ -286,6 +325,16 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
description = self._sch.get_description(self.path, self.method)
|
||||
return description
|
||||
|
||||
def get_security(self):
|
||||
"""Return a list of security requirements for this operation.
|
||||
|
||||
Returning an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
|
||||
authentication schemes). Returning ``None`` will inherit the top-level secuirty requirements.
|
||||
|
||||
:return: security requirements
|
||||
:rtype: list[dict[str,list[str]]]"""
|
||||
return self.overrides.get('security', None)
|
||||
|
||||
def get_tags(self, operation_keys):
|
||||
"""Get a list of tags for this operation. Tags determine how operations relate with each other, and in the UI
|
||||
each tag will show as a group containing the operations that use it.
|
||||
@@ -301,7 +350,11 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
|
||||
:rtype: list[str]
|
||||
"""
|
||||
media_types = [parser.media_type for parser in getattr(self.view, 'parser_classes', [])]
|
||||
if all(is_form_media_type(encoding) for encoding in media_types):
|
||||
return media_types
|
||||
return media_types[:1]
|
||||
return get_consumes(getattr(self.view, 'parser_classes', []))
|
||||
|
||||
def get_produces(self):
|
||||
"""Return the MIME types this endpoint can produce.
|
||||
|
||||
:rtype: list[str]
|
||||
"""
|
||||
return get_produces(getattr(self.view, 'renderer_classes', []))
|
||||
|
||||
@@ -2,8 +2,9 @@ import json
|
||||
import logging
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
from importlib import import_module
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.management.base import BaseCommand
|
||||
from rest_framework.test import APIRequestFactory, force_authenticate
|
||||
@@ -12,7 +13,15 @@ from rest_framework.views import APIView
|
||||
from ... import openapi
|
||||
from ...app_settings import swagger_settings
|
||||
from ...codecs import OpenAPICodecJson, OpenAPICodecYaml
|
||||
from ...generators import OpenAPISchemaGenerator
|
||||
|
||||
|
||||
def import_class(import_string):
|
||||
if not import_string:
|
||||
return None
|
||||
|
||||
module_path, class_name = import_string.rsplit('.', 1)
|
||||
module = import_module(module_path)
|
||||
return getattr(module, class_name)
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
@@ -42,7 +51,7 @@ class Command(BaseCommand):
|
||||
'-u', '--url', dest='api_url',
|
||||
default='',
|
||||
type=str,
|
||||
help='Base API URL - sets the host, scheme and basePath attributes of the generated document.'
|
||||
help='Base API URL - sets the host and scheme attributes of the generated document.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-m', '--mock-request', dest='mock',
|
||||
@@ -50,9 +59,13 @@ class Command(BaseCommand):
|
||||
help='Use a mock request when generating the swagger schema. This is useful if your views or serializers'
|
||||
'depend on context from a request in order to function.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--api-version', dest='api_version',
|
||||
type=str,
|
||||
help='Version to use to generate schema. This option implies --mock-request.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--user', dest='user',
|
||||
default='',
|
||||
help='Username of an existing user to use for mocked authentication. This option implies --mock-request.'
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -64,6 +77,11 @@ class Command(BaseCommand):
|
||||
'OpenAPISchemaGenerator.get_schema().\n'
|
||||
'This option implies --mock-request.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-g', '--generator-class', dest='generator_class_name',
|
||||
default='',
|
||||
help='Import string pointing to an OpenAPISchemaGenerator subclass to use for schema generation.'
|
||||
)
|
||||
|
||||
def write_schema(self, schema, stream, format):
|
||||
if format == 'json':
|
||||
@@ -89,7 +107,8 @@ class Command(BaseCommand):
|
||||
request = APIView().initialize_request(request)
|
||||
return request
|
||||
|
||||
def handle(self, output_file, overwrite, format, api_url, mock, user, private, *args, **options):
|
||||
def handle(self, output_file, overwrite, format, api_url, mock, api_version, user, private, generator_class_name,
|
||||
*args, **kwargs):
|
||||
# disable logs of WARNING and below
|
||||
logging.disable(logging.WARNING)
|
||||
|
||||
@@ -107,19 +126,30 @@ class Command(BaseCommand):
|
||||
|
||||
api_url = api_url or swagger_settings.DEFAULT_API_URL
|
||||
|
||||
user = User.objects.get(username=user) if user else None
|
||||
mock = mock or private or (user is not None)
|
||||
if user:
|
||||
# Only call get_user_model if --user was passed in order to
|
||||
# avoid crashing if auth is not configured in the project
|
||||
user = get_user_model().objects.get(username=user)
|
||||
|
||||
mock = mock or private or (user is not None) or (api_version is not None)
|
||||
if mock and not api_url:
|
||||
raise ImproperlyConfigured(
|
||||
'--mock-request requires an API url; either provide '
|
||||
'the --url argument or set the DEFAULT_API_URL setting'
|
||||
)
|
||||
|
||||
request = self.get_mock_request(api_url, format, user) if mock else None
|
||||
request = None
|
||||
if mock:
|
||||
request = self.get_mock_request(api_url, format, user)
|
||||
|
||||
generator = OpenAPISchemaGenerator(
|
||||
if request and api_version:
|
||||
request.version = api_version
|
||||
|
||||
generator_class = import_class(generator_class_name) or swagger_settings.DEFAULT_GENERATOR_CLASS
|
||||
generator = generator_class(
|
||||
info=info,
|
||||
url=api_url
|
||||
version=api_version,
|
||||
url=api_url,
|
||||
)
|
||||
schema = generator.get_schema(request=request, public=not private)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ class SwaggerExceptionMiddleware(object):
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
if isinstance(exception, SwaggerValidationError):
|
||||
err = {'errors': {exception.validator_name: str(exception)}}
|
||||
err = {'errors': exception.errors, 'message': str(exception)}
|
||||
codec = exception.source_codec
|
||||
if isinstance(codec, _OpenAPICodec):
|
||||
err = codec.encode_error(err)
|
||||
|
||||
+88
-21
@@ -2,6 +2,7 @@ import re
|
||||
from collections import OrderedDict
|
||||
|
||||
from coreapi.compat import urlparse
|
||||
from django.urls import get_script_prefix
|
||||
from inflection import camelize
|
||||
|
||||
from .utils import filter_none
|
||||
@@ -34,6 +35,7 @@ FORMAT_URI = "uri" #:
|
||||
# pulled out of my ass
|
||||
FORMAT_UUID = "uuid" #:
|
||||
FORMAT_SLUG = "slug" #:
|
||||
FORMAT_DECIMAL = "decimal"
|
||||
|
||||
IN_BODY = 'body' #:
|
||||
IN_PATH = 'path' #:
|
||||
@@ -114,7 +116,7 @@ class SwaggerDict(OrderedDict):
|
||||
which would result in the extra attributes being added first. For this reason, we defer the insertion of the
|
||||
attributes and require that subclasses call ._insert_extras__ at the end of their __init__ method.
|
||||
"""
|
||||
for attr, val in self._extras__.items():
|
||||
for attr, val in sorted(self._extras__.items()):
|
||||
setattr(self, attr, val)
|
||||
|
||||
@staticmethod
|
||||
@@ -210,12 +212,19 @@ class Info(SwaggerDict):
|
||||
|
||||
|
||||
class Swagger(SwaggerDict):
|
||||
def __init__(self, info=None, _url=None, _version=None, paths=None, definitions=None, **extra):
|
||||
def __init__(self, info=None, _url=None, _prefix=None, _version=None, consumes=None, produces=None,
|
||||
security_definitions=None, security=None, paths=None, definitions=None, **extra):
|
||||
"""Root Swagger object.
|
||||
|
||||
:param .Info info: info object
|
||||
:param str _url: URL used for guessing the API host, scheme and basepath
|
||||
:param str _url: URL used for setting the API host and scheme
|
||||
:param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi
|
||||
SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable
|
||||
:param str _version: version string to override Info
|
||||
:param dict[str,dict[str,str]] security_definitions: list of supported authentication mechanisms
|
||||
:param list[dict] security: authentication mechanisms accepted by default; can be overriden in Operation
|
||||
:param list[str] consumes: consumed MIME types; can be overriden in Operation
|
||||
:param list[str] produces: produced MIME types; can be overriden in Operation
|
||||
:param .Paths paths: paths object
|
||||
:param dict[str,.Schema] definitions: named models
|
||||
"""
|
||||
@@ -226,16 +235,43 @@ class Swagger(SwaggerDict):
|
||||
|
||||
if _url:
|
||||
url = urlparse.urlparse(_url)
|
||||
if url.netloc:
|
||||
self.host = url.netloc
|
||||
if url.scheme:
|
||||
self.schemes = [url.scheme]
|
||||
self.base_path = '/'
|
||||
assert url.netloc and url.scheme, "if given, url must have both schema and netloc"
|
||||
self.host = url.netloc
|
||||
self.schemes = [url.scheme]
|
||||
|
||||
self.base_path = self.get_base_path(get_script_prefix(), _prefix)
|
||||
self.consumes = consumes
|
||||
self.produces = produces
|
||||
self.security_definitions = filter_none(security_definitions)
|
||||
self.security = filter_none(security)
|
||||
self.paths = paths
|
||||
self.definitions = filter_none(definitions)
|
||||
self._insert_extras__()
|
||||
|
||||
@classmethod
|
||||
def get_base_path(cls, script_prefix, api_prefix):
|
||||
"""Determine an appropriate value for ``basePath`` based on the SCRIPT_NAME and the api common prefix.
|
||||
|
||||
:param str script_prefix: script prefix as defined by django ``get_script_prefix``
|
||||
:param str api_prefix: api common prefix
|
||||
:return: joined base path
|
||||
"""
|
||||
# avoid double slash when joining script_name with api_prefix
|
||||
if script_prefix and script_prefix.endswith('/'):
|
||||
script_prefix = script_prefix[:-1]
|
||||
if not api_prefix.startswith('/'):
|
||||
api_prefix = '/' + api_prefix
|
||||
|
||||
base_path = script_prefix + api_prefix
|
||||
|
||||
# ensure that the base path has a leading slash and no trailing slash
|
||||
if base_path and base_path.endswith('/'):
|
||||
base_path = base_path[:-1]
|
||||
if not base_path.startswith('/'):
|
||||
base_path = '/' + base_path
|
||||
|
||||
return base_path
|
||||
|
||||
|
||||
class Paths(SwaggerDict):
|
||||
def __init__(self, paths, **extra):
|
||||
@@ -278,8 +314,8 @@ class PathItem(SwaggerDict):
|
||||
|
||||
|
||||
class Operation(SwaggerDict):
|
||||
def __init__(self, operation_id, responses, parameters=None, consumes=None,
|
||||
produces=None, summary=None, description=None, tags=None, **extra):
|
||||
def __init__(self, operation_id, responses, parameters=None, consumes=None, produces=None, summary=None,
|
||||
description=None, tags=None, security=None, **extra):
|
||||
"""Information about an API operation (path + http method combination)
|
||||
|
||||
:param str operation_id: operation ID, should be unique across all operations
|
||||
@@ -290,6 +326,7 @@ class Operation(SwaggerDict):
|
||||
:param str summary: operation summary; should be < 120 characters
|
||||
:param str description: operation description; can be of any length and supports markdown
|
||||
:param list[str] tags: operation tags
|
||||
:param list[dict[str,list[str]]] security: list of security requirements
|
||||
"""
|
||||
super(Operation, self).__init__(**extra)
|
||||
self.operation_id = operation_id
|
||||
@@ -300,6 +337,7 @@ class Operation(SwaggerDict):
|
||||
self.consumes = filter_none(consumes)
|
||||
self.produces = filter_none(produces)
|
||||
self.tags = filter_none(tags)
|
||||
self.security = filter_none(security)
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
@@ -321,11 +359,15 @@ class Items(SwaggerDict):
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self._insert_extras__()
|
||||
if items and type != TYPE_ARRAY:
|
||||
raise AssertionError("items can only be used when type is array")
|
||||
if pattern and type != TYPE_STRING:
|
||||
raise AssertionError("pattern can only be used when type is string")
|
||||
|
||||
|
||||
class Parameter(SwaggerDict):
|
||||
def __init__(self, name, in_, description=None, required=None, schema=None,
|
||||
type=None, format=None, enum=None, pattern=None, items=None, **extra):
|
||||
type=None, format=None, enum=None, pattern=None, items=None, default=None, **extra):
|
||||
"""Describe parameters accepted by an :class:`.Operation`. Each parameter should be a unique combination of
|
||||
(`name`, `in_`). ``body`` and ``form`` parameters in the same operation are mutually exclusive.
|
||||
|
||||
@@ -339,6 +381,7 @@ class Parameter(SwaggerDict):
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param .Items items: only valid if `type` is ``array``
|
||||
:param default: default value if the parameter is not provided; must conform to parameter type
|
||||
"""
|
||||
super(Parameter, self).__init__(**extra)
|
||||
if (not schema and not type) or (schema and type):
|
||||
@@ -353,7 +396,20 @@ class Parameter(SwaggerDict):
|
||||
self.enum = enum
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self.default = default
|
||||
self._insert_extras__()
|
||||
if self['in'] == IN_PATH:
|
||||
# path parameters must always be required
|
||||
assert required is not False, "path parameter cannot be optional"
|
||||
self.required = True
|
||||
if self['in'] != IN_BODY and schema is not None:
|
||||
raise AssertionError("schema can only be applied to a body Parameter, not %s" % type)
|
||||
if (format or enum or pattern or default) and not type:
|
||||
raise AssertionError("[format, enum, pattern, default] can only be applied to non-body Parameter")
|
||||
if items and type != TYPE_ARRAY:
|
||||
raise AssertionError("items can only be used when type is array")
|
||||
if pattern and type != TYPE_STRING:
|
||||
raise AssertionError("pattern can only be used when type is string")
|
||||
|
||||
|
||||
class Schema(SwaggerDict):
|
||||
@@ -369,7 +425,7 @@ class Schema(SwaggerDict):
|
||||
:param str format: value format, see OpenAPI spec
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param list[.Schema,.SchemaRef] properties: object properties; required if `type` is ``object``
|
||||
:param dict[str,(.Schema,.SchemaRef)] properties: object properties; required if `type` is ``object``
|
||||
:param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties`
|
||||
:param list[str] required: list of requried property names
|
||||
:param .Schema,.SchemaRef items: type of array items, only valid if `type` is ``array``
|
||||
@@ -381,9 +437,9 @@ class Schema(SwaggerDict):
|
||||
super(Schema, self).__init__(**extra)
|
||||
if required is True or required is False:
|
||||
# common error
|
||||
raise AssertionError(
|
||||
"the `requires` attribute of schema must be an array of required properties, not a boolean!")
|
||||
assert type is not None, "type is required!"
|
||||
raise AssertionError("the `required` attribute of schema must be an "
|
||||
"array of required property names, not a boolean!")
|
||||
assert type, "type is required!"
|
||||
self.title = title
|
||||
self.description = description
|
||||
self.required = filter_none(required)
|
||||
@@ -397,12 +453,20 @@ class Schema(SwaggerDict):
|
||||
self.read_only = read_only
|
||||
self.default = default
|
||||
self._insert_extras__()
|
||||
if (properties or (additional_properties is not None)) and type != TYPE_OBJECT:
|
||||
raise AssertionError("only object Schema can have properties")
|
||||
if (format or enum or pattern) and type in (TYPE_OBJECT, TYPE_ARRAY):
|
||||
raise AssertionError("[format, enum, pattern] can only be applied to primitive Schema")
|
||||
if items and type != TYPE_ARRAY:
|
||||
raise AssertionError("items can only be used when type is array")
|
||||
if pattern and type != TYPE_STRING:
|
||||
raise AssertionError("pattern can only be used when type is string")
|
||||
|
||||
|
||||
class _Ref(SwaggerDict):
|
||||
ref_name_re = re.compile(r"#/(?P<scope>.+)/(?P<name>[^/]+)$")
|
||||
|
||||
def __init__(self, resolver, name, scope, expected_type):
|
||||
def __init__(self, resolver, name, scope, expected_type, ignore_unresolved=False):
|
||||
"""Base class for all reference types. A reference object has only one property, ``$ref``, which must be a JSON
|
||||
reference to a valid object in the specification, e.g. ``#/definitions/Article`` to refer to an article model.
|
||||
|
||||
@@ -410,13 +474,15 @@ class _Ref(SwaggerDict):
|
||||
:param str name: referenced object name, e.g. "Article"
|
||||
:param str scope: reference scope, e.g. "definitions"
|
||||
:param type[.SwaggerDict] expected_type: the expected type that will be asserted on the object found in resolver
|
||||
:param bool ignore_unresolved: allow the reference to be not defined in resolver
|
||||
"""
|
||||
super(_Ref, self).__init__()
|
||||
assert not type(self) == _Ref, "do not instantiate _Ref directly"
|
||||
ref_name = "#/{scope}/{name}".format(scope=scope, name=name)
|
||||
obj = resolver.get(name, scope)
|
||||
assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \
|
||||
.format(actual=type(obj).__name__, expected=expected_type.__name__)
|
||||
if not ignore_unresolved:
|
||||
obj = resolver.get(name, scope)
|
||||
assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \
|
||||
.format(actual=type(obj).__name__, expected=expected_type.__name__)
|
||||
self.ref = ref_name
|
||||
|
||||
def resolve(self, resolver):
|
||||
@@ -438,14 +504,15 @@ class _Ref(SwaggerDict):
|
||||
|
||||
|
||||
class SchemaRef(_Ref):
|
||||
def __init__(self, resolver, schema_name):
|
||||
def __init__(self, resolver, schema_name, ignore_unresolved=False):
|
||||
"""Adds a reference to a named Schema defined in the ``#/definitions/`` object.
|
||||
|
||||
:param .ReferenceResolver resolver: component resolver which must contain the definition
|
||||
:param str schema_name: schema name
|
||||
:param bool ignore_unresolved: allow the reference to be not defined in resolver
|
||||
"""
|
||||
assert SCHEMA_DEFINITIONS in resolver.scopes
|
||||
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema)
|
||||
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema, ignore_unresolved)
|
||||
|
||||
|
||||
Schema.OR_REF = (Schema, SchemaRef)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
from django.shortcuts import render, resolve_url
|
||||
from rest_framework.renderers import BaseRenderer
|
||||
from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer
|
||||
from rest_framework.utils import json
|
||||
|
||||
from drf_yasg.openapi import Swagger
|
||||
|
||||
from .app_settings import redoc_settings, swagger_settings
|
||||
from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
|
||||
|
||||
|
||||
class _SpecRenderer(BaseRenderer):
|
||||
"""Base class for text renderers. Handles encoding and validation."""
|
||||
charset = None
|
||||
validators = ['ssv', 'flex']
|
||||
charset = 'utf-8'
|
||||
validators = []
|
||||
codec_class = None
|
||||
|
||||
@classmethod
|
||||
@@ -20,6 +22,12 @@ class _SpecRenderer(BaseRenderer):
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
assert self.codec_class, "must override codec_class"
|
||||
codec = self.codec_class(self.validators)
|
||||
|
||||
if not isinstance(data, Swagger): # pragma: no cover
|
||||
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
|
||||
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
|
||||
# see https://github.com/axnsan12/drf-yasg/issues/58
|
||||
return JSONRenderer().render(data, media_type, renderer_context)
|
||||
return codec.encode(data)
|
||||
|
||||
|
||||
@@ -51,6 +59,11 @@ class _UIRenderer(BaseRenderer):
|
||||
template = ''
|
||||
|
||||
def render(self, swagger, accepted_media_type=None, renderer_context=None):
|
||||
if not isinstance(swagger, Swagger): # pragma: no cover
|
||||
# if `swagger` is not a ``Swagger`` object, it means we somehow got a non-success ``Response``
|
||||
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
|
||||
# see https://github.com/axnsan12/drf-yasg/issues/58
|
||||
return TemplateHTMLRenderer().render(swagger, accepted_media_type, renderer_context)
|
||||
self.set_context(renderer_context, swagger)
|
||||
return render(
|
||||
renderer_context['request'],
|
||||
@@ -63,6 +76,7 @@ class _UIRenderer(BaseRenderer):
|
||||
renderer_context['version'] = swagger.info.version
|
||||
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['USE_SESSION_AUTH'] = swagger_settings.USE_SESSION_AUTH
|
||||
renderer_context.update(self.get_auth_urls())
|
||||
|
||||
@@ -85,6 +99,9 @@ class _UIRenderer(BaseRenderer):
|
||||
'defaultModelRendering': swagger_settings.DEFAULT_MODEL_RENDERING,
|
||||
'defaultModelExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
|
||||
'defaultModelsExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
|
||||
'showCommonExtensions': swagger_settings.SHOW_COMMON_EXTENSIONS,
|
||||
'oauth2RedirectUrl': swagger_settings.OAUTH2_REDIRECT_URL,
|
||||
'supportedSubmitMethods': swagger_settings.SUPPORTED_SUBMIT_METHODS,
|
||||
}
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if swagger_settings.VALIDATOR_URL != '':
|
||||
@@ -102,6 +119,11 @@ class _UIRenderer(BaseRenderer):
|
||||
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
var redoc = document.createElement("redoc");
|
||||
redoc.setAttribute("spec-url", specURL);
|
||||
|
||||
var redocSettings = JSON.parse(document.getElementById('redoc-settings').innerHTML);
|
||||
if (redocSettings.lazyRendering) {
|
||||
redoc.setAttribute("lazy-rendering", '');
|
||||
}
|
||||
if (redocSettings.pathInMiddle) {
|
||||
redoc.setAttribute("path-in-middle-panel", '');
|
||||
}
|
||||
if (redocSettings.hideHostname) {
|
||||
redoc.setAttribute("hide-hostname", '');
|
||||
}
|
||||
redoc.setAttribute("expand-responses", redocSettings.expandResponses);
|
||||
document.body.appendChild(redoc);
|
||||
|
||||
function hideEmptyVersion() {
|
||||
// 'span.api-info-version' is for redoc 1.x, 'div.api-info span' is for redoc 2-alpha
|
||||
var apiVersion = document.querySelector('span.api-info-version') || document.querySelector('div.api-info span');
|
||||
if (!apiVersion) {
|
||||
console.log("WARNING: could not find API versionString element (span.api-info-version)");
|
||||
return;
|
||||
}
|
||||
|
||||
var versionString = apiVersion.innerText;
|
||||
if (versionString) {
|
||||
// trim spaces and surrounding ()
|
||||
versionString = versionString.replace(/ /g,'');
|
||||
versionString = versionString.replace(/(^\()|(\)$)/g,'');
|
||||
}
|
||||
|
||||
if (!versionString) {
|
||||
// hide version element if empty
|
||||
apiVersion.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
if (document.querySelector('span.api-info-version') || document.querySelector('div.api-info span')) {
|
||||
hideEmptyVersion();
|
||||
}
|
||||
else {
|
||||
insertionQ('span.api-info-version').every(hideEmptyVersion);
|
||||
insertionQ('div.api-info span').every(hideEmptyVersion);
|
||||
}
|
||||
+113
-3
File diff suppressed because one or more lines are too long
@@ -0,0 +1,77 @@
|
||||
html {
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
*,
|
||||
*:before,
|
||||
*:after {
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body.swagger-body {
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
#django-session-auth {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#django-session-auth > div {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize {
|
||||
padding: 10px 23px;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize a {
|
||||
color: #49cc90;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#django-session-auth .hello {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
#django-session-auth .hello .django-session {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: inline;
|
||||
padding: .2em .6em .3em;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
vertical-align: baseline;
|
||||
border-radius: .25em;
|
||||
}
|
||||
|
||||
.label-primary {
|
||||
background-color: #337ab7;
|
||||
}
|
||||
|
||||
.divider {
|
||||
margin-right: 8px;
|
||||
background: #16222c44;
|
||||
width: 2px;
|
||||
}
|
||||
|
||||
svg.swagger-defs {
|
||||
position: absolute;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
@@ -45,11 +45,18 @@
|
||||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
let oauthErrorMsg
|
||||
if (qp.error) {
|
||||
oauthErrorMsg = "["+qp.error+"]: " +
|
||||
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
|
||||
(qp.error_uri ? "More info: "+qp.error_uri : "");
|
||||
}
|
||||
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "error",
|
||||
message: "Authorization failed: no accessCode received from the server"
|
||||
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
|
||||
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
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
|
||||
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')) {
|
||||
console.log("WARNING: session auth already patched; skipping patchSwaggerUi()");
|
||||
return;
|
||||
}
|
||||
|
||||
authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
|
||||
djangoSessionAuth.classList.remove("hidden");
|
||||
|
||||
var divider = document.createElement("div");
|
||||
divider.classList.add("divider");
|
||||
authWrapper.insertBefore(divider, authorizeButton);
|
||||
}
|
||||
|
||||
function initSwaggerUi() {
|
||||
if (window.ui) {
|
||||
console.log("WARNING: skipping initSwaggerUi() because window.ui is already defined");
|
||||
return;
|
||||
}
|
||||
var swaggerConfig = {
|
||||
url: specURL,
|
||||
dom_id: '#swagger-ui',
|
||||
displayOperationId: true,
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML);
|
||||
if (!('oauth2RedirectUrl' in swaggerSettings)) {
|
||||
var oauth2RedirectUrl = document.getElementById('oauth2-redirect-url');
|
||||
if (oauth2RedirectUrl) {
|
||||
swaggerSettings['oauth2RedirectUrl'] = oauth2RedirectUrl.href;
|
||||
oauth2RedirectUrl.parentNode.removeChild(oauth2RedirectUrl);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(swaggerSettings);
|
||||
for (var p in swaggerSettings) {
|
||||
if (swaggerSettings.hasOwnProperty(p)) {
|
||||
swaggerConfig[p] = swaggerSettings[p];
|
||||
}
|
||||
}
|
||||
window.ui = SwaggerUIBundle(swaggerConfig);
|
||||
|
||||
var oauth2Config = JSON.parse(document.getElementById('oauth2-config').innerHTML);
|
||||
console.log(oauth2Config);
|
||||
window.ui.initOAuth(oauth2Config);
|
||||
}
|
||||
|
||||
window.onload = function () {
|
||||
initSwaggerUi();
|
||||
};
|
||||
|
||||
if (document.querySelector('.auth-wrapper .authorize')) {
|
||||
patchSwaggerUi();
|
||||
}
|
||||
else {
|
||||
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
|
||||
}
|
||||
@@ -5,39 +5,14 @@
|
||||
<title>{{ title }}</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
{% if not request.version %}
|
||||
span.api-info-version {
|
||||
display: none;
|
||||
}
|
||||
{% endif %}
|
||||
</style>
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
var redoc = document.createElement("redoc");
|
||||
redoc.setAttribute("spec-url", specURL);
|
||||
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
|
||||
|
||||
var redocSettings = {};
|
||||
redocSettings = {{ redoc_settings | safe }};
|
||||
if (redocSettings.lazyRendering) {
|
||||
redoc.setAttribute("lazy-rendering", '');
|
||||
}
|
||||
if (redocSettings.pathInMiddle) {
|
||||
redoc.setAttribute("path-in-middle-panel", '');
|
||||
}
|
||||
if (redocSettings.hideHostname) {
|
||||
redoc.setAttribute("hide-hostname", '');
|
||||
}
|
||||
redoc.setAttribute("expand-responses", redocSettings.expandResponses);
|
||||
document.body.appendChild(redoc);
|
||||
</script>
|
||||
<script src="{% static 'drf-yasg/redoc/redoc.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/redoc/redoc.min.js' %}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -5,88 +5,18 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ title }}</title>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700"
|
||||
rel="stylesheet">
|
||||
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700">
|
||||
<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' %}">
|
||||
<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"/>
|
||||
<style>
|
||||
html {
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
<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"/>
|
||||
|
||||
*,
|
||||
*:before,
|
||||
*:after {
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
#django-session-auth {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#django-session-auth > div {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize {
|
||||
padding: 10px 23px;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize a {
|
||||
color: #49cc90;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#django-session-auth .hello {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
#django-session-auth .hello .django-session {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: inline;
|
||||
padding: .2em .6em .3em;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
vertical-align: baseline;
|
||||
border-radius: .25em;
|
||||
}
|
||||
|
||||
.label-primary {
|
||||
background-color: #337ab7;
|
||||
}
|
||||
|
||||
.divider {
|
||||
margin-right: 8px;
|
||||
background: #16222c44;
|
||||
width: 2px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<body class="swagger-body">
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;width:0;height:0">
|
||||
<svg class="swagger-defs" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 20 20" id="unlocked">
|
||||
<path
|
||||
@@ -128,73 +58,16 @@
|
||||
<div id="swagger-ui"></div>
|
||||
<div id="spec-error" class="hidden alert alert-danger"></div>
|
||||
|
||||
<script>
|
||||
"use strict";
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
|
||||
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')) {
|
||||
console.log("session auth already patched");
|
||||
return;
|
||||
}
|
||||
|
||||
authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
|
||||
djangoSessionAuth.classList.remove("hidden");
|
||||
|
||||
var divider = document.createElement("div");
|
||||
divider.classList.add("divider");
|
||||
authWrapper.insertBefore(divider, authorizeButton);
|
||||
}
|
||||
|
||||
function initSwaggerUi() {
|
||||
var swaggerConfig = {
|
||||
url: specURL,
|
||||
dom_id: '#swagger-ui',
|
||||
displayOperationId: true,
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
var swaggerSettings = {};
|
||||
swaggerSettings = {{ swagger_settings | safe }};
|
||||
console.log(swaggerSettings);
|
||||
for (var p in swaggerSettings) {
|
||||
if (swaggerSettings.hasOwnProperty(p)) {
|
||||
swaggerConfig[p] = swaggerSettings[p];
|
||||
}
|
||||
}
|
||||
window.ui = SwaggerUIBundle(swaggerConfig);
|
||||
}
|
||||
|
||||
window.onload = function () {
|
||||
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
|
||||
initSwaggerUi();
|
||||
};
|
||||
</script>
|
||||
<script id="swagger-settings" type="application/json">{{ swagger_settings | 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>
|
||||
<script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-standalone-preset.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/swagger-ui-init.js' %}"></script>
|
||||
|
||||
<a id="oauth2-redirect-url" href="{% static 'drf-yasg/swagger-ui-dist/oauth2-redirect.html' %}" class="hidden"></a>
|
||||
|
||||
<div id="django-session-auth" class="hidden">
|
||||
{% if USE_SESSION_AUTH %}
|
||||
|
||||
+116
-23
@@ -2,19 +2,30 @@ import inspect
|
||||
import logging
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.db import models
|
||||
from django.utils.encoding import force_text
|
||||
from rest_framework import serializers, status
|
||||
from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin
|
||||
from rest_framework.request import is_form_media_type
|
||||
from rest_framework.settings import api_settings as rest_framework_settings
|
||||
from rest_framework.views import APIView
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: used to forcibly remove the body of a request via :func:`.swagger_auto_schema`
|
||||
no_body = object()
|
||||
|
||||
class no_body(object):
|
||||
"""Used as a sentinel value to forcibly remove the body of a request via :func:`.swagger_auto_schema`."""
|
||||
pass
|
||||
|
||||
|
||||
def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_body=None, query_serializer=None,
|
||||
manual_parameters=None, operation_id=None, operation_description=None, responses=None,
|
||||
field_inspectors=None, filter_inspectors=None, paginator_inspectors=None,
|
||||
class unset(object):
|
||||
"""Used as a sentinel value for function parameters not set by the caller where ``None`` would be a valid value."""
|
||||
pass
|
||||
|
||||
|
||||
def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_body=None, query_serializer=None,
|
||||
manual_parameters=None, operation_id=None, operation_description=None, security=None,
|
||||
responses=None, field_inspectors=None, filter_inspectors=None, paginator_inspectors=None,
|
||||
**extra_overrides):
|
||||
"""Decorate a view method to customize the :class:`.Operation` object generated from it.
|
||||
|
||||
@@ -23,18 +34,12 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
|
||||
The `auto_schema` and `operation_description` arguments take precendence over view- or method-level values.
|
||||
|
||||
.. versionchanged:: 1.1
|
||||
Added the ``extra_overrides`` and ``operatiod_id`` parameters.
|
||||
|
||||
.. versionchanged:: 1.1
|
||||
Added the ``field_inspectors``, ``filter_inspectors`` and ``paginator_inspectors`` parameters.
|
||||
|
||||
:param str method: for multi-method views, the http method the options should apply to
|
||||
:param list[str] methods: for multi-method views, the http methods the options should apply to
|
||||
:param .inspectors.SwaggerAutoSchema auto_schema: custom class to use for generating the Operation object;
|
||||
this overrides both the class-level ``swagger_schema`` attribute and the ``DEFAULT_AUTO_SCHEMA_CLASS``
|
||||
setting
|
||||
:param .Schema,.SchemaRef,.Serializer request_body: custom request body, or :data:`.no_body`. The value given here
|
||||
setting, and can be set to ``None`` to prevent this operation from being generated
|
||||
:param .Schema,.SchemaRef,.Serializer request_body: custom request body, or :class:`.no_body`. The value given here
|
||||
will be used as the ``schema`` property of a :class:`.Parameter` with ``in: 'body'``.
|
||||
|
||||
A Schema or SchemaRef is not valid if this request consumes form-data, because ``form`` and ``body`` parameters
|
||||
@@ -62,6 +67,9 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
|
||||
: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 list[dict] security: security requirements override; used to specify which authetication mechanism
|
||||
is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
|
||||
authentication schemes), and ``None`` will inherit the top-level secuirty requirements
|
||||
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
|
||||
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
|
||||
@@ -69,6 +77,8 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
|
||||
* if a plain string is given as value, a :class:`.Response` with no body and that string as its description
|
||||
will be generated
|
||||
* if ``None`` is given as a value, the response is ignored; this is mainly useful for disabling default
|
||||
2xx responses, i.e. ``responses={200: None, 302: 'something'}``
|
||||
* if a :class:`.Schema`, :class:`.SchemaRef` is given, a :class:`.Response` with the schema as its body and
|
||||
an empty description will be generated
|
||||
* a ``Serializer`` class or instance will be converted into a :class:`.Schema` and treated as above
|
||||
@@ -88,34 +98,38 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
def decorator(view_method):
|
||||
assert not any(hm in extra_overrides for hm in APIView.http_method_names), "HTTP method names not allowed here"
|
||||
data = {
|
||||
'auto_schema': auto_schema,
|
||||
'request_body': request_body,
|
||||
'query_serializer': query_serializer,
|
||||
'manual_parameters': manual_parameters,
|
||||
'operation_id': operation_id,
|
||||
'operation_description': operation_description,
|
||||
'security': security,
|
||||
'responses': responses,
|
||||
'filter_inspectors': list(filter_inspectors) if filter_inspectors else None,
|
||||
'paginator_inspectors': list(paginator_inspectors) if paginator_inspectors else None,
|
||||
'field_inspectors': list(field_inspectors) if field_inspectors else None,
|
||||
}
|
||||
data = filter_none(data)
|
||||
if auto_schema is not unset:
|
||||
data['auto_schema'] = auto_schema
|
||||
data.update(extra_overrides)
|
||||
if not data: # pragma: no cover
|
||||
# no overrides to set, no use in doing more work
|
||||
return
|
||||
|
||||
# if the method is a detail_route or list_route, it will have a bind_to_methods attribute
|
||||
# if the method is an @action, it will have a bind_to_methods attribute
|
||||
bind_to_methods = getattr(view_method, 'bind_to_methods', [])
|
||||
# if the method is actually a function based view (@api_view), it will have a 'cls' attribute
|
||||
view_cls = getattr(view_method, 'cls', None)
|
||||
http_method_names = getattr(view_cls, 'http_method_names', [])
|
||||
http_method_names = [m for m in getattr(view_cls, 'http_method_names', []) if hasattr(view_cls, m)]
|
||||
|
||||
available_methods = http_method_names + bind_to_methods
|
||||
existing_data = getattr(view_method, '_swagger_auto_schema', {})
|
||||
|
||||
_methods = methods
|
||||
if methods or method:
|
||||
assert available_methods or http_method_names, "`method` or `methods` can only be specified " \
|
||||
"on @action or @api_view views"
|
||||
assert bool(methods) != bool(method), "specify either method or methods"
|
||||
assert not isinstance(methods, str), "`methods` expects to receive a list of methods;" \
|
||||
" use `method` for a single argument"
|
||||
@@ -127,24 +141,28 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
assert not any(mth in existing_data for mth in _methods), "http method defined multiple times"
|
||||
|
||||
if available_methods:
|
||||
# detail_route, list_route or api_view
|
||||
# action or api_view
|
||||
assert bool(http_method_names) != bool(bind_to_methods), "this should never happen"
|
||||
|
||||
if len(available_methods) > 1:
|
||||
assert _methods, \
|
||||
"on multi-method api_view, detail_route or list_route, you must specify swagger_auto_schema on " \
|
||||
"a per-method basis using one of the `method` or `methods` arguments"
|
||||
"on multi-method api_view, action, detail_route or list_route, you must specify " \
|
||||
"swagger_auto_schema on a per-method basis using one of the `method` or `methods` arguments"
|
||||
else:
|
||||
# for a single-method view we assume that single method as the decorator target
|
||||
_methods = _methods or available_methods
|
||||
|
||||
assert not any(hasattr(getattr(view_cls, mth, None), '_swagger_auto_schema') for mth in _methods), \
|
||||
"swagger_auto_schema applied twice to method"
|
||||
assert not any(mth in existing_data for mth in _methods), "swagger_auto_schema applied twice to method"
|
||||
existing_data.update((mth.lower(), data) for mth in _methods)
|
||||
view_method._swagger_auto_schema = existing_data
|
||||
else:
|
||||
assert not _methods, \
|
||||
"the methods argument should only be specified when decorating a detail_route or list_route; you " \
|
||||
"should also ensure that you put the swagger_auto_schema decorator AFTER (above) the _route decorator"
|
||||
assert not existing_data, "a single view method should only be decorated once"
|
||||
"the methods argument should only be specified when decorating an action, detail_route or " \
|
||||
"list_route; you should also ensure that you put the swagger_auto_schema decorator " \
|
||||
"AFTER (above) the _route decorator"
|
||||
assert not existing_data, "swagger_auto_schema applied twice to method"
|
||||
view_method._swagger_auto_schema = data
|
||||
|
||||
return view_method
|
||||
@@ -169,7 +187,7 @@ def is_list_view(path, method, view):
|
||||
return True
|
||||
|
||||
if action in ('retrieve', 'update', 'partial_update', 'destroy') or detail is True or suffix == 'Instance':
|
||||
# a detail_route is surely not a list route
|
||||
# a detail action is surely not a list route
|
||||
return False
|
||||
|
||||
# for GenericAPIView, if it's a detail view it can't also be a list view
|
||||
@@ -241,3 +259,78 @@ def force_serializer_instance(serializer):
|
||||
assert isinstance(serializer, serializers.BaseSerializer), \
|
||||
"Serializer class or instance required, not %s" % type(serializer).__name__
|
||||
return serializer
|
||||
|
||||
|
||||
def get_consumes(parser_classes):
|
||||
"""Extract ``consumes`` MIME types from a list of parser classes.
|
||||
|
||||
:param list parser_classes: parser classes
|
||||
:return: MIME types for ``consumes``
|
||||
:rtype: list[str]
|
||||
"""
|
||||
media_types = [parser.media_type for parser in parser_classes or []]
|
||||
if all(is_form_media_type(encoding) for encoding in media_types):
|
||||
return media_types
|
||||
else:
|
||||
media_types = [encoding for encoding in media_types if not is_form_media_type(encoding)]
|
||||
return media_types
|
||||
|
||||
|
||||
def get_produces(renderer_classes):
|
||||
"""Extract ``produces`` MIME types from a list of renderer classes.
|
||||
|
||||
:param list renderer_classes: renderer classes
|
||||
:return: MIME types for ``produces``
|
||||
:rtype: list[str]
|
||||
"""
|
||||
media_types = [renderer.media_type for renderer in renderer_classes or []]
|
||||
media_types = [encoding for encoding in media_types if 'html' not in encoding]
|
||||
return media_types
|
||||
|
||||
|
||||
def decimal_as_float(field):
|
||||
"""
|
||||
Returns true if ``field`` is a django-rest-framework DecimalField and its ``coerce_to_string`` attribute or the
|
||||
``COERCE_DECIMAL_TO_STRING`` setting is set to ``False``.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if isinstance(field, serializers.DecimalField) or isinstance(field, models.DecimalField):
|
||||
return not getattr(field, 'coerce_to_string', rest_framework_settings.COERCE_DECIMAL_TO_STRING)
|
||||
return False
|
||||
|
||||
|
||||
def get_serializer_ref_name(serializer):
|
||||
"""
|
||||
Get serializer's ref_name (or None for ModelSerializer if it is named 'NestedSerializer')
|
||||
|
||||
:param serializer: Serializer instance
|
||||
:return: Serializer's ``ref_name`` or ``None`` for inline serializer
|
||||
:rtype: str
|
||||
"""
|
||||
serializer_meta = getattr(serializer, 'Meta', None)
|
||||
serializer_name = type(serializer).__name__
|
||||
if hasattr(serializer_meta, 'ref_name'):
|
||||
ref_name = serializer_meta.ref_name
|
||||
elif serializer_name == 'NestedSerializer' and isinstance(serializer, serializers.ModelSerializer):
|
||||
logger.debug("Forcing inline output for ModelSerializer named 'NestedSerializer': " + str(serializer))
|
||||
ref_name = None
|
||||
else:
|
||||
ref_name = serializer_name
|
||||
if ref_name.endswith('Serializer'):
|
||||
ref_name = ref_name[:-len('Serializer')]
|
||||
return ref_name
|
||||
|
||||
|
||||
def force_real_str(s, encoding='utf-8', strings_only=False, errors='strict'):
|
||||
"""
|
||||
Force `s` into a ``str`` instance.
|
||||
|
||||
Fix for https://github.com/axnsan12/drf-yasg/issues/159
|
||||
"""
|
||||
if s is not None:
|
||||
s = force_text(s, encoding, strings_only, errors)
|
||||
if type(s) != str:
|
||||
s = '' + s
|
||||
|
||||
return s
|
||||
|
||||
@@ -11,7 +11,6 @@ from rest_framework.settings import api_settings
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from .app_settings import swagger_settings
|
||||
from .generators import OpenAPISchemaGenerator
|
||||
from .renderers import OpenAPIRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
|
||||
|
||||
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
|
||||
@@ -46,17 +45,16 @@ def deferred_never_cache(view_func):
|
||||
|
||||
|
||||
def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None,
|
||||
generator_class=OpenAPISchemaGenerator,
|
||||
generator_class=swagger_settings.DEFAULT_GENERATOR_CLASS,
|
||||
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
|
||||
permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
|
||||
"""
|
||||
Create a SchemaView class with default renderers and generators.
|
||||
"""Create a SchemaView class with default renderers and generators.
|
||||
|
||||
:param .Info info: Swagger API Info object; if omitted, defaults to `DEFAULT_INFO`
|
||||
:param str url: API base url; if left blank will be deduced from the location the view is served at
|
||||
:param patterns: passed to SchemaGenerator
|
||||
:param urlconf: passed to SchemaGenerator
|
||||
:param bool public: if False, includes only endpoints the current user has access to
|
||||
:param .Info info: information about the API; if omitted, defaults to :ref:`DEFAULT_INFO <default-swagger-settings>`
|
||||
:param str url: same as :class:`.OpenAPISchemaGenerator`
|
||||
:param patterns: same as :class:`.OpenAPISchemaGenerator`
|
||||
:param urlconf: same as :class:`.OpenAPISchemaGenerator`
|
||||
:param bool public: if False, includes only the endpoints that are accesible by the user viewing the schema
|
||||
:param list validators: a list of validator names to apply; allowed values are ``flex``, ``ssv``
|
||||
:param type generator_class: schema generator class to use; should be a subclass of :class:`.OpenAPISchemaGenerator`
|
||||
:param tuple authentication_classes: authentication classes for the schema view itself
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# Generated by Django 2.0 on 2017-12-23 09:07
|
||||
# Generated by Django 2.0.1 on 2018-03-18 18:32
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
@@ -23,8 +24,28 @@ class Migration(migrations.Migration):
|
||||
('slug', models.SlugField(blank=True, help_text='slug model help_text', unique=True)),
|
||||
('date_created', models.DateTimeField(auto_now_add=True)),
|
||||
('date_modified', models.DateTimeField(auto_now=True)),
|
||||
('article_type', models.PositiveSmallIntegerField(choices=[(1, 'first'), (2, 'second'), (3, 'third'), (7, 'seven'), (8, 'eight')], help_text='IntegerField declared on model with choices=(...) and exposed via ModelSerializer', null=True)),
|
||||
('cover', models.ImageField(blank=True, upload_to='article/original/')),
|
||||
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='articles', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ArticleGroup',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('title', models.CharField(help_text='title model help_text', max_length=255, unique=True)),
|
||||
('slug', models.SlugField(blank=True, help_text='slug model help_text', unique=True)),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='article',
|
||||
name='group',
|
||||
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.PROTECT, related_name='articles_as_main', to='articles.ArticleGroup'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='article',
|
||||
name='original_group',
|
||||
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.PROTECT, related_name='articles_as_original', to='articles.ArticleGroup'),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import uuid
|
||||
|
||||
from django.db import models
|
||||
|
||||
|
||||
@@ -8,5 +10,20 @@ class Article(models.Model):
|
||||
date_created = models.DateTimeField(auto_now_add=True)
|
||||
date_modified = models.DateTimeField(auto_now=True)
|
||||
author = models.ForeignKey('auth.User', related_name='articles', on_delete=models.CASCADE)
|
||||
article_type = models.PositiveSmallIntegerField(
|
||||
help_text="IntegerField declared on model with choices=(...) and exposed via ModelSerializer",
|
||||
choices=((1, "first"), (2, "second"), (3, "third"), (7, "seven"), (8, "eight")), null=True
|
||||
)
|
||||
|
||||
cover = models.ImageField(upload_to='article/original/', blank=True)
|
||||
group = models.ForeignKey('ArticleGroup', related_name='articles_as_main', blank=True, default=None,
|
||||
on_delete=models.PROTECT)
|
||||
original_group = models.ForeignKey('ArticleGroup', related_name='articles_as_original', blank=True, default=None,
|
||||
on_delete=models.PROTECT)
|
||||
|
||||
|
||||
class ArticleGroup(models.Model):
|
||||
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
|
||||
|
||||
title = models.CharField(help_text="title model help_text", max_length=255, blank=False, unique=True)
|
||||
slug = models.SlugField(help_text="slug model help_text", unique=True, blank=True)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from rest_framework import serializers
|
||||
|
||||
from articles.models import Article
|
||||
from articles.models import Article, ArticleGroup
|
||||
|
||||
|
||||
class ArticleSerializer(serializers.ModelSerializer):
|
||||
@@ -11,12 +11,14 @@ class ArticleSerializer(serializers.ModelSerializer):
|
||||
read_only=True,
|
||||
)
|
||||
uuid = serializers.UUIDField(help_text="should articles have UUIDs?", read_only=True)
|
||||
cover_name = serializers.FileField(use_url=False, source='cover', read_only=True)
|
||||
cover_name = serializers.FileField(use_url=False, source='cover', required=True)
|
||||
group = serializers.SlugRelatedField(slug_field='uuid', queryset=ArticleGroup.objects.all())
|
||||
original_group = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Article
|
||||
fields = ('title', 'author', 'body', 'slug', 'date_created', 'date_modified',
|
||||
'references', 'uuid', 'cover', 'cover_name')
|
||||
'references', 'uuid', 'cover', 'cover_name', 'article_type', 'group', 'original_group', )
|
||||
read_only_fields = ('date_created', 'date_modified',
|
||||
'references', 'uuid', 'cover_name')
|
||||
lookup_field = 'slug'
|
||||
@@ -31,7 +33,7 @@ class ArticleSerializer(serializers.ModelSerializer):
|
||||
|
||||
|
||||
class ImageUploadSerializer(serializers.Serializer):
|
||||
what_am_i_doing = serializers.RegexField(regex=r"^69$", help_text="test")
|
||||
what_am_i_doing = serializers.RegexField(regex=r"^69$", help_text="test", default="69")
|
||||
image_styles = serializers.ListSerializer(
|
||||
child=serializers.ChoiceField(choices=['wide', 'tall', 'thumb', 'social']),
|
||||
help_text="Parameter with Items"
|
||||
|
||||
+42
-16
@@ -3,6 +3,7 @@ import datetime
|
||||
from django.utils.decorators import method_decorator
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from rest_framework import viewsets
|
||||
# noinspection PyDeprecation
|
||||
from rest_framework.decorators import detail_route, list_route
|
||||
from rest_framework.filters import OrderingFilter
|
||||
from rest_framework.pagination import LimitOffsetPagination
|
||||
@@ -89,23 +90,48 @@ class ArticleViewSet(viewsets.ModelViewSet):
|
||||
|
||||
swagger_schema = NoTitleAutoSchema
|
||||
|
||||
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
|
||||
@list_route(methods=['get'])
|
||||
def today(self, request):
|
||||
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
|
||||
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
|
||||
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
|
||||
serializer = self.serializer_class(articles, many=True)
|
||||
return Response(serializer.data)
|
||||
try:
|
||||
from rest_framework.decorators import action
|
||||
|
||||
@swagger_auto_schema(method='get', operation_description="image GET description override")
|
||||
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
|
||||
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
|
||||
def image(self, request, slug=None):
|
||||
"""
|
||||
image method docstring
|
||||
"""
|
||||
pass
|
||||
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
|
||||
@action(detail=False, methods=['get'])
|
||||
def today(self, request):
|
||||
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
|
||||
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
|
||||
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
|
||||
serializer = self.serializer_class(articles, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
@swagger_auto_schema(method='get', operation_description="image GET description override")
|
||||
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
|
||||
@action(detail=True, methods=['get', 'post'], parser_classes=(MultiPartParser,))
|
||||
def image(self, request, slug=None):
|
||||
"""
|
||||
image method docstring
|
||||
"""
|
||||
pass
|
||||
except ImportError:
|
||||
action = None
|
||||
|
||||
# noinspection PyDeprecation
|
||||
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
|
||||
@list_route(methods=['get'])
|
||||
def today(self, request):
|
||||
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
|
||||
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
|
||||
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
|
||||
serializer = self.serializer_class(articles, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
# noinspection PyDeprecation
|
||||
@swagger_auto_schema(method='get', operation_description="image GET description override")
|
||||
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
|
||||
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
|
||||
def image(self, request, slug=None):
|
||||
"""
|
||||
image method docstring
|
||||
"""
|
||||
pass
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
"""update method docstring"""
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
from __future__ import print_function
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.db.utils import IntegrityError
|
||||
|
||||
username = 'admin'
|
||||
email = 'admin@admin.admin'
|
||||
password = 'passwordadmin'
|
||||
User.objects.filter(username=username).delete()
|
||||
User.objects.create_superuser(username, email, password)
|
||||
|
||||
print("Created superuser '%s <%s>' with password '%s'" % (username, email, password))
|
||||
try:
|
||||
User.objects.create_superuser(username, email, password)
|
||||
except IntegrityError:
|
||||
print("User '%s <%s>' already exists" % (username, email))
|
||||
else:
|
||||
print("Created superuser '%s <%s>' with password '%s'" % (username, email, password))
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings.local")
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PeopleConfig(AppConfig):
|
||||
name = 'people'
|
||||
@@ -0,0 +1,30 @@
|
||||
# Generated by Django 2.0.1 on 2018-03-18 18:32
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Identity',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('firstName', models.CharField(max_length=30, null=True)),
|
||||
('lastName', models.CharField(max_length=30, null=True)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Person',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('identity', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='person', to='people.Identity')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.db import models
|
||||
from django.utils.safestring import mark_safe
|
||||
|
||||
|
||||
class Identity(models.Model):
|
||||
firstName = models.CharField(max_length=30, null=True)
|
||||
lastName = models.CharField(max_length=30, null=True, help_text=mark_safe("<strong>Here's some HTML!</strong>"))
|
||||
|
||||
|
||||
class Person(models.Model):
|
||||
identity = models.OneToOneField(Identity, related_name='person', on_delete=models.PROTECT)
|
||||
@@ -0,0 +1,23 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import Identity, Person
|
||||
|
||||
|
||||
class IdentitySerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Identity
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class PersonSerializer(serializers.ModelSerializer):
|
||||
identity = IdentitySerializer()
|
||||
|
||||
class Meta:
|
||||
model = Person
|
||||
fields = '__all__'
|
||||
|
||||
def create(self, validated_data):
|
||||
identity = Identity(**validated_data['identity'])
|
||||
identity.save()
|
||||
validated_data['identity'] = identity
|
||||
return super().create(validated_data)
|
||||
@@ -0,0 +1,26 @@
|
||||
from django.conf.urls import url
|
||||
|
||||
from .views import IdentityViewSet, PersonViewSet
|
||||
|
||||
person_list = PersonViewSet.as_view({
|
||||
'get': 'list',
|
||||
'post': 'create'
|
||||
})
|
||||
person_detail = PersonViewSet.as_view({
|
||||
'get': 'retrieve',
|
||||
'patch': 'partial_update',
|
||||
'delete': 'destroy'
|
||||
})
|
||||
|
||||
identity_detail = IdentityViewSet.as_view({
|
||||
'get': 'retrieve',
|
||||
'patch': 'partial_update',
|
||||
})
|
||||
|
||||
urlpatterns = (
|
||||
url(r'^$', person_list, name='people-list'),
|
||||
url(r'^(?P<pk>[0-9]+)$', person_detail, name='person-detail'),
|
||||
|
||||
url(r'^(?P<person>[0-9]+)/identity$', identity_detail,
|
||||
name='person-identity'),
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
from rest_framework import viewsets
|
||||
|
||||
from .models import Identity, Person
|
||||
from .serializers import IdentitySerializer, PersonSerializer
|
||||
|
||||
|
||||
class PersonViewSet(viewsets.ModelViewSet):
|
||||
model = Person
|
||||
queryset = Person.objects
|
||||
serializer_class = PersonSerializer
|
||||
|
||||
|
||||
class IdentityViewSet(viewsets.ModelViewSet):
|
||||
model = Identity
|
||||
queryset = Identity.objects
|
||||
serializer_class = IdentitySerializer
|
||||
@@ -1,3 +1,2 @@
|
||||
drf-yasg[validation]
|
||||
Django>=1.11.7
|
||||
..[validation]
|
||||
-r ../requirements/testproj.txt
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Generated by Django 2.0 on 2017-12-23 09:07
|
||||
# Generated by Django 2.0.1 on 2018-03-18 18:32
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from rest_framework import serializers
|
||||
from rest_framework.compat import MinValueValidator
|
||||
|
||||
from snippets.models import LANGUAGE_CHOICES, STYLE_CHOICES, Snippet
|
||||
|
||||
|
||||
class LanguageSerializer(serializers.Serializer):
|
||||
|
||||
name = serializers.ChoiceField(
|
||||
choices=LANGUAGE_CHOICES, default='python', help_text='The name of the programming language')
|
||||
|
||||
@@ -14,7 +16,6 @@ class LanguageSerializer(serializers.Serializer):
|
||||
|
||||
|
||||
class ExampleProjectSerializer(serializers.Serializer):
|
||||
|
||||
project_name = serializers.CharField(help_text='Name of the project')
|
||||
github_repo = serializers.CharField(required=True, help_text='Github repository of the project')
|
||||
|
||||
@@ -49,6 +50,10 @@ class SnippetSerializer(serializers.Serializer):
|
||||
example_projects = serializers.ListSerializer(child=ExampleProjectSerializer(), read_only=True)
|
||||
difficulty_factor = serializers.FloatField(help_text="this is here just to test FloatField",
|
||||
read_only=True, default=lambda: 6.9)
|
||||
rate_as_string = serializers.DecimalField(max_digits=6, decimal_places=3, default=Decimal('0.0'),
|
||||
validators=[MinValueValidator(Decimal('0.0'))])
|
||||
rate = serializers.DecimalField(max_digits=6, decimal_places=3, default=Decimal('0.0'), coerce_to_string=False,
|
||||
validators=[MinValueValidator(Decimal('0.0'))])
|
||||
|
||||
def create(self, validated_data):
|
||||
"""
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
from djangorestframework_camel_case.parser import CamelCaseJSONParser
|
||||
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
|
||||
from inflection import camelize
|
||||
from rest_framework import generics
|
||||
from rest_framework import generics, status
|
||||
from rest_framework.parsers import FormParser
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.inspectors import SwaggerAutoSchema
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
|
||||
@@ -19,7 +22,7 @@ class SnippetList(generics.ListCreateAPIView):
|
||||
queryset = Snippet.objects.all()
|
||||
serializer_class = SnippetSerializer
|
||||
|
||||
parser_classes = (CamelCaseJSONParser,)
|
||||
parser_classes = (FormParser, CamelCaseJSONParser,)
|
||||
renderer_classes = (CamelCaseJSONRenderer,)
|
||||
swagger_schema = CamelCaseOperationIDAutoSchema
|
||||
|
||||
@@ -30,6 +33,21 @@ class SnippetList(generics.ListCreateAPIView):
|
||||
"""post method docstring"""
|
||||
return super(SnippetList, self).post(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(
|
||||
operation_id='snippets_delete_bulk',
|
||||
request_body=openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties={
|
||||
'body': openapi.Schema(
|
||||
type=openapi.TYPE_STRING,
|
||||
description='this should not crash (request body on DELETE method)'
|
||||
)
|
||||
}
|
||||
),
|
||||
)
|
||||
def delete(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
"""
|
||||
@@ -53,6 +71,26 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
"""patch method docstring"""
|
||||
return super(SnippetDetail, self).patch(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(
|
||||
manual_parameters=[
|
||||
openapi.Parameter(
|
||||
name='id', in_=openapi.IN_PATH,
|
||||
type=openapi.TYPE_INTEGER,
|
||||
description="path parameter override",
|
||||
required=True
|
||||
),
|
||||
openapi.Parameter(
|
||||
name='delete_form_param', in_=openapi.IN_FORM,
|
||||
type=openapi.TYPE_INTEGER,
|
||||
description="this should not crash (form parameter on DELETE method)"
|
||||
),
|
||||
],
|
||||
responses={
|
||||
status.HTTP_204_NO_CONTENT: openapi.Response(
|
||||
description="this should not crash (response object with no schema)"
|
||||
)
|
||||
}
|
||||
)
|
||||
def delete(self, request, *args, **kwargs):
|
||||
"""delete method docstring"""
|
||||
return super(SnippetDetail, self).patch(request, *args, **kwargs)
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
import os
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '!z1yj(9uz)zk0gg@5--j)bc4h^i!8))r^dezco8glf190e0&#p'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
ALLOWED_HOSTS = [
|
||||
'127.0.0.1',
|
||||
@@ -35,6 +26,8 @@ INSTALLED_APPS = [
|
||||
'snippets',
|
||||
'users',
|
||||
'articles',
|
||||
'todo',
|
||||
'people'
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
@@ -69,16 +62,6 @@ TEMPLATES = [
|
||||
|
||||
WSGI_APPLICATION = 'testproj.wsgi.application'
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
|
||||
|
||||
@@ -97,18 +80,32 @@ AUTH_PASSWORD_VALIDATORS = [
|
||||
},
|
||||
]
|
||||
|
||||
# Django Rest Framework
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
)
|
||||
}
|
||||
|
||||
# drf-yasg
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'LOGIN_URL': '/admin/login',
|
||||
'LOGOUT_URL': '/admin/logout',
|
||||
'VALIDATOR_URL': 'http://localhost:8189',
|
||||
|
||||
'DEFAULT_INFO': 'testproj.urls.swagger_info'
|
||||
'DEFAULT_INFO': 'testproj.urls.swagger_info',
|
||||
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'Basic': {
|
||||
'type': 'basic'
|
||||
},
|
||||
'Bearer': {
|
||||
'type': 'apiKey',
|
||||
'name': 'Authorization',
|
||||
'in': 'header'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
@@ -128,9 +125,14 @@ USE_TZ = True
|
||||
# https://docs.djangoproject.com/en/1.11/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
|
||||
|
||||
# Testing
|
||||
|
||||
TEST_RUNNER = 'testproj.runner.PytestTestRunner'
|
||||
|
||||
# Logging configuration
|
||||
|
||||
LOGGING = {
|
||||
'version': 1,
|
||||
'disable_existing_loggers': True,
|
||||
@@ -0,0 +1,35 @@
|
||||
import dj_database_url
|
||||
|
||||
from .base import * # noqa: F403
|
||||
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS.append('.herokuapp.com')
|
||||
|
||||
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
|
||||
assert SECRET_KEY, 'DJANGO_SECRET_KEY environment variable must be set'
|
||||
|
||||
SESSION_COOKIE_SECURE = True
|
||||
CSRF_COOKIE_SECURE = True
|
||||
|
||||
SECURE_BROWSER_XSS_FILTER = True
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
X_FRAME_OPTIONS = 'DENY'
|
||||
|
||||
# Simplified static file serving.
|
||||
# https://warehouse.python.org/project/whitenoise/
|
||||
|
||||
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
||||
MIDDLEWARE.insert(0, 'whitenoise.middleware.WhiteNoiseMiddleware')
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': dj_database_url.config(conn_max_age=600)
|
||||
}
|
||||
|
||||
SILENCED_SYSTEM_CHECKS = [
|
||||
'security.W004', # SECURE_HSTS_SECONDS
|
||||
'security.W008', # SECURE_SSL_REDIRECT
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
|
||||
import dj_database_url
|
||||
|
||||
from .base import * # noqa: F403
|
||||
|
||||
SWAGGER_SETTINGS.update({'VALIDATOR_URL': 'http://localhost:8189'})
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
|
||||
|
||||
db_path = os.path.join(BASE_DIR, 'db.sqlite3')
|
||||
DATABASES = {
|
||||
'default': dj_database_url.parse('sqlite:///' + db_path)
|
||||
}
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '!z1yj(9uz)zk0gg@5--j)bc4h^i!8))r^dezco8glf190e0&#p'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
@@ -1,5 +1,7 @@
|
||||
import user_agents
|
||||
from django.conf.urls import include, url
|
||||
from django.contrib import admin
|
||||
from django.shortcuts import redirect
|
||||
from rest_framework import permissions
|
||||
from rest_framework.decorators import api_view
|
||||
|
||||
@@ -9,7 +11,13 @@ from drf_yasg.views import get_schema_view
|
||||
swagger_info = openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
description="Test description",
|
||||
description="""This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg) Django Rest Framework library.
|
||||
|
||||
The `swagger-ui` view can be found [here](/cached/swagger).
|
||||
The `ReDoc` view can be found [here](/cached/redoc).
|
||||
The swagger YAML document can be found [here](/cached/swagger.yaml).
|
||||
|
||||
You can log in using the pre-existing `admin` user with password `passwordadmin`.""", # noqa
|
||||
terms_of_service="https://www.google.com/policies/terms/",
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
@@ -27,17 +35,34 @@ def plain_view(request):
|
||||
pass
|
||||
|
||||
|
||||
def root_redirect(request):
|
||||
user_agent_string = request.META.get('HTTP_USER_AGENT', '')
|
||||
user_agent = user_agents.parse(user_agent_string)
|
||||
|
||||
if user_agent.is_mobile:
|
||||
schema_view = 'cschema-redoc'
|
||||
else:
|
||||
schema_view = 'cschema-swagger-ui'
|
||||
|
||||
return redirect(schema_view, permanent=True)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
|
||||
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
|
||||
url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
|
||||
|
||||
url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'),
|
||||
url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'),
|
||||
url(r'^cached/redoc/$', SchemaView.with_ui('redoc', cache_timeout=None), name='cschema-redoc'),
|
||||
|
||||
url(r'^$', root_redirect),
|
||||
|
||||
url(r'^admin/', admin.site.urls),
|
||||
url(r'^snippets/', include('snippets.urls')),
|
||||
url(r'^articles/', include('articles.urls')),
|
||||
url(r'^users/', include('users.urls')),
|
||||
url(r'^todo/', include('todo.urls')),
|
||||
url(r'^people/', include('people.urls')),
|
||||
url(r'^plain/', plain_view),
|
||||
]
|
||||
|
||||
@@ -2,6 +2,6 @@ import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings.local")
|
||||
|
||||
application = get_wsgi_application()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Generated by Django 2.0.1 on 2018-03-18 18:32
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Todo',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=50)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TodoAnother',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('todo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='todo.Todo')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TodoYetAnother',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('todo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='todo.TodoAnother')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
# Generated by Django 2.0.4 on 2018-04-26 13:06
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
('todo', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='TodoTree',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('parent', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name='children', to='todo.TodoTree')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,20 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Todo(models.Model):
|
||||
title = models.CharField(max_length=50)
|
||||
|
||||
|
||||
class TodoAnother(models.Model):
|
||||
todo = models.ForeignKey(Todo, on_delete=models.CASCADE)
|
||||
title = models.CharField(max_length=50)
|
||||
|
||||
|
||||
class TodoYetAnother(models.Model):
|
||||
todo = models.ForeignKey(TodoAnother, on_delete=models.CASCADE)
|
||||
title = models.CharField(max_length=50)
|
||||
|
||||
|
||||
class TodoTree(models.Model):
|
||||
parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True)
|
||||
title = models.CharField(max_length=50)
|
||||
@@ -0,0 +1,58 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.utils import timezone
|
||||
from rest_framework import serializers
|
||||
from rest_framework_recursive.fields import RecursiveField
|
||||
|
||||
from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
|
||||
|
||||
|
||||
class TodoSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Todo
|
||||
fields = ('title', 'a_hidden_field',)
|
||||
|
||||
a_hidden_field = serializers.HiddenField(default=timezone.now)
|
||||
|
||||
|
||||
class TodoAnotherSerializer(serializers.ModelSerializer):
|
||||
todo = TodoSerializer()
|
||||
|
||||
class Meta:
|
||||
model = TodoAnother
|
||||
fields = ('title', 'todo')
|
||||
|
||||
|
||||
class TodoYetAnotherSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = TodoYetAnother
|
||||
fields = ('title', 'todo')
|
||||
depth = 2
|
||||
swagger_schema_fields = {
|
||||
'example': OrderedDict([
|
||||
('title', 'parent'),
|
||||
('todo', OrderedDict([
|
||||
('title', 'child'),
|
||||
('todo', None),
|
||||
])),
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
class TodoTreeSerializer(serializers.ModelSerializer):
|
||||
children = serializers.ListField(child=RecursiveField(), source='children.all')
|
||||
|
||||
class Meta:
|
||||
model = TodoTree
|
||||
fields = ('id', 'title', 'children')
|
||||
|
||||
|
||||
class TodoRecursiveSerializer(serializers.ModelSerializer):
|
||||
parent = RecursiveField(read_only=True)
|
||||
parent_id = serializers.PrimaryKeyRelatedField(queryset=TodoTree.objects.all(), pk_field=serializers.IntegerField(),
|
||||
write_only=True, allow_null=True, required=False, default=None,
|
||||
source='parent')
|
||||
|
||||
class Meta:
|
||||
model = TodoTree
|
||||
fields = ('id', 'title', 'parent', 'parent_id')
|
||||
@@ -0,0 +1,18 @@
|
||||
from django.conf.urls import url
|
||||
from rest_framework import routers
|
||||
|
||||
from todo import views
|
||||
|
||||
router = routers.DefaultRouter()
|
||||
router.register(r'', views.TodoViewSet)
|
||||
router.register(r'another', views.TodoAnotherViewSet)
|
||||
router.register(r'yetanother', views.TodoYetAnotherViewSet)
|
||||
router.register(r'tree', views.TodoTreeView)
|
||||
router.register(r'recursive', views.TodoRecursiveView)
|
||||
|
||||
urlpatterns = router.urls
|
||||
|
||||
urlpatterns += [
|
||||
url(r'^(?P<todo_id>\d+)/yetanothers/(?P<yetanother_id>\d+)/$',
|
||||
views.NestedTodoView.as_view(), ),
|
||||
]
|
||||
@@ -0,0 +1,77 @@
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.generics import RetrieveAPIView
|
||||
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
|
||||
from .models import Todo, TodoAnother, TodoTree, TodoYetAnother
|
||||
from .serializer import (
|
||||
TodoAnotherSerializer, TodoRecursiveSerializer, TodoSerializer, TodoTreeSerializer, TodoYetAnotherSerializer
|
||||
)
|
||||
|
||||
|
||||
class TodoViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = Todo.objects.all()
|
||||
serializer_class = TodoSerializer
|
||||
|
||||
lookup_field = 'id'
|
||||
lookup_value_regex = '[0-9]+'
|
||||
|
||||
|
||||
class TodoAnotherViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = TodoAnother.objects.all()
|
||||
serializer_class = TodoAnotherSerializer
|
||||
|
||||
|
||||
class TodoYetAnotherViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = TodoYetAnother.objects.all()
|
||||
serializer_class = TodoYetAnotherSerializer
|
||||
|
||||
|
||||
class NestedTodoView(RetrieveAPIView):
|
||||
serializer_class = TodoYetAnotherSerializer
|
||||
|
||||
|
||||
class TodoTreeView(viewsets.ReadOnlyModelViewSet):
|
||||
queryset = TodoTree.objects.all()
|
||||
|
||||
def get_serializer_class(self):
|
||||
if getattr(self, 'swagger_fake_view', False):
|
||||
return TodoTreeSerializer
|
||||
|
||||
raise NotImplementedError("must not call this")
|
||||
|
||||
|
||||
class TodoRecursiveView(viewsets.ModelViewSet):
|
||||
queryset = TodoTree.objects.all()
|
||||
|
||||
def get_serializer(self, *args, **kwargs):
|
||||
raise NotImplementedError("must not call this")
|
||||
|
||||
def get_serializer_class(self):
|
||||
raise NotImplementedError("must not call this")
|
||||
|
||||
def get_serializer_context(self):
|
||||
raise NotImplementedError("must not call this")
|
||||
|
||||
@swagger_auto_schema(request_body=TodoRecursiveSerializer)
|
||||
def create(self, request, *args, **kwargs):
|
||||
return super(TodoRecursiveView, self).create(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(responses={200: None, 302: 'Redirect somewhere'})
|
||||
def retrieve(self, request, *args, **kwargs):
|
||||
return super(TodoRecursiveView, self).retrieve(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(request_body=TodoRecursiveSerializer)
|
||||
def update(self, request, *args, **kwargs):
|
||||
return super(TodoRecursiveView, self).update(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(request_body=TodoRecursiveSerializer)
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
return super(TodoRecursiveView, self).update(request, *args, **kwargs)
|
||||
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
return super(TodoRecursiveView, self).destroy(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(responses={200: TodoRecursiveSerializer(many=True)})
|
||||
def list(self, request, *args, **kwargs):
|
||||
return super(TodoRecursiveView, self).list(request, *args, **kwargs)
|
||||
+11
-7
@@ -19,13 +19,17 @@ class UserList(APIView):
|
||||
serializer = UserSerializerrr(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
@swagger_auto_schema(operation_description="apiview post description override", request_body=openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
required=['username'],
|
||||
properties={
|
||||
'username': openapi.Schema(type=openapi.TYPE_STRING)
|
||||
},
|
||||
))
|
||||
@swagger_auto_schema(
|
||||
operation_description="apiview post description override",
|
||||
request_body=openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
required=['username'],
|
||||
properties={
|
||||
'username': openapi.Schema(type=openapi.TYPE_STRING)
|
||||
},
|
||||
),
|
||||
security=[]
|
||||
)
|
||||
def post(self, request):
|
||||
serializer = UserSerializerrr(request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from six import StringIO
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
@@ -6,6 +8,7 @@ from collections import OrderedDict
|
||||
import pytest
|
||||
from datadiff.tools import assert_equal
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management import call_command
|
||||
from rest_framework.test import APIRequestFactory
|
||||
from rest_framework.views import APIView
|
||||
|
||||
@@ -64,6 +67,21 @@ def validate_schema(db):
|
||||
return validate_schema
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def call_generate_swagger():
|
||||
def call_generate_swagger(output_file='-', overwrite=False, format='', api_url='',
|
||||
mock=False, user=None, private=False, generator_class_name='', **kwargs):
|
||||
out = StringIO()
|
||||
call_command(
|
||||
'generate_swagger', stdout=out,
|
||||
output_file=output_file, overwrite=overwrite, format=format, api_url=api_url, mock=mock, user=user,
|
||||
private=private, generator_class_name=generator_class_name, **kwargs
|
||||
)
|
||||
return out.getvalue()
|
||||
|
||||
return call_generate_swagger
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def compare_schemas():
|
||||
def compare_schemas(schema1, schema2):
|
||||
|
||||
+575
-52
@@ -1,7 +1,11 @@
|
||||
swagger: '2.0'
|
||||
info:
|
||||
title: Snippets API
|
||||
description: Test description
|
||||
description: "This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg)\
|
||||
\ Django Rest Framework library.\n\nThe `swagger-ui` view can be found [here](/cached/swagger).\
|
||||
\ \nThe `ReDoc` view can be found [here](/cached/redoc). \nThe swagger YAML\
|
||||
\ document can be found [here](/cached/swagger.yaml). \n\nYou can log in using\
|
||||
\ the pre-existing `admin` user with password `passwordadmin`."
|
||||
termsOfService: https://www.google.com/policies/terms/
|
||||
contact:
|
||||
email: contact@snippets.local
|
||||
@@ -12,6 +16,20 @@ host: test.local:8002
|
||||
schemes:
|
||||
- http
|
||||
basePath: /
|
||||
consumes:
|
||||
- application/json
|
||||
produces:
|
||||
- application/json
|
||||
securityDefinitions:
|
||||
Basic:
|
||||
type: basic
|
||||
Bearer:
|
||||
in: header
|
||||
name: Authorization
|
||||
type: apiKey
|
||||
security:
|
||||
- Basic: []
|
||||
- Bearer: []
|
||||
paths:
|
||||
/articles/:
|
||||
get:
|
||||
@@ -59,8 +77,6 @@ paths:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Article'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
post:
|
||||
@@ -77,8 +93,6 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Article'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
parameters: []
|
||||
@@ -104,8 +118,6 @@ paths:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Article'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
parameters: []
|
||||
@@ -119,8 +131,6 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Article'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
put:
|
||||
@@ -137,8 +147,6 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Article'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
patch:
|
||||
@@ -157,8 +165,6 @@ paths:
|
||||
$ref: '#/definitions/Article'
|
||||
'404':
|
||||
description: slug not found
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
delete:
|
||||
@@ -168,8 +174,6 @@ paths:
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- articles
|
||||
parameters:
|
||||
@@ -199,9 +203,11 @@ paths:
|
||||
- name: what_am_i_doing
|
||||
in: formData
|
||||
description: test
|
||||
required: true
|
||||
required: false
|
||||
type: string
|
||||
pattern: ^69$
|
||||
default: '69'
|
||||
minLength: 1
|
||||
- name: image_styles
|
||||
in: formData
|
||||
description: Parameter with Items
|
||||
@@ -234,6 +240,113 @@ paths:
|
||||
type: string
|
||||
format: slug
|
||||
pattern: '[a-z0-9]+(?:-[a-z0-9]+)'
|
||||
/people/:
|
||||
get:
|
||||
operationId: people_list
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Person'
|
||||
tags:
|
||||
- people
|
||||
post:
|
||||
operationId: people_create
|
||||
description: ''
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/Person'
|
||||
responses:
|
||||
'201':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Person'
|
||||
tags:
|
||||
- people
|
||||
parameters: []
|
||||
/people/{id}:
|
||||
get:
|
||||
operationId: people_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Person'
|
||||
tags:
|
||||
- people
|
||||
patch:
|
||||
operationId: people_partial_update
|
||||
description: ''
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/Person'
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Person'
|
||||
tags:
|
||||
- people
|
||||
delete:
|
||||
operationId: people_delete
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
tags:
|
||||
- people
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: A unique integer value identifying this person.
|
||||
required: true
|
||||
type: integer
|
||||
/people/{person}/identity:
|
||||
get:
|
||||
operationId: people_identity_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Identity'
|
||||
tags:
|
||||
- people
|
||||
patch:
|
||||
operationId: people_identity_partial_update
|
||||
description: ''
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/Identity'
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Identity'
|
||||
tags:
|
||||
- people
|
||||
parameters:
|
||||
- name: person
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
/plain/:
|
||||
get:
|
||||
operationId: plain_list
|
||||
@@ -242,8 +355,6 @@ paths:
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- plain
|
||||
parameters: []
|
||||
@@ -259,8 +370,6 @@ paths:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Snippet'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- snippets
|
||||
post:
|
||||
@@ -277,8 +386,24 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Snippet'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- snippets
|
||||
delete:
|
||||
operationId: snippetsDeleteBulk
|
||||
description: SnippetList classdoc
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
body:
|
||||
description: this should not crash (request body on DELETE method)
|
||||
type: string
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
tags:
|
||||
- snippets
|
||||
parameters: []
|
||||
@@ -292,8 +417,6 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Snippet'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- snippets
|
||||
put:
|
||||
@@ -310,8 +433,6 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Snippet'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- snippets
|
||||
patch:
|
||||
@@ -328,19 +449,24 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Snippet'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- snippets
|
||||
delete:
|
||||
operationId: snippetsDelete
|
||||
description: delete method docstring
|
||||
parameters: []
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: path parameter override
|
||||
required: true
|
||||
type: integer
|
||||
- name: delete_form_param
|
||||
in: formData
|
||||
description: this should not crash (form parameter on DELETE method)
|
||||
type: integer
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
consumes:
|
||||
- application/json
|
||||
description: this should not crash (response object with no schema)
|
||||
tags:
|
||||
- snippets
|
||||
parameters:
|
||||
@@ -349,6 +475,247 @@ paths:
|
||||
description: A unique integer value identifying this snippet.
|
||||
required: true
|
||||
type: integer
|
||||
/todo/:
|
||||
get:
|
||||
operationId: todo_list
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Todo'
|
||||
tags:
|
||||
- todo
|
||||
parameters: []
|
||||
/todo/another/:
|
||||
get:
|
||||
operationId: todo_another_list
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/TodoAnother'
|
||||
tags:
|
||||
- todo
|
||||
parameters: []
|
||||
/todo/another/{id}/:
|
||||
get:
|
||||
operationId: todo_another_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoAnother'
|
||||
tags:
|
||||
- todo
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: A unique integer value identifying this todo another.
|
||||
required: true
|
||||
type: integer
|
||||
/todo/recursive/:
|
||||
get:
|
||||
operationId: todo_recursive_list
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
tags:
|
||||
- todo
|
||||
post:
|
||||
operationId: todo_recursive_create
|
||||
description: ''
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
responses:
|
||||
'201':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
tags:
|
||||
- todo
|
||||
parameters: []
|
||||
/todo/recursive/{id}/:
|
||||
get:
|
||||
operationId: todo_recursive_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'302':
|
||||
description: Redirect somewhere
|
||||
tags:
|
||||
- todo
|
||||
put:
|
||||
operationId: todo_recursive_update
|
||||
description: ''
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
tags:
|
||||
- todo
|
||||
patch:
|
||||
operationId: todo_recursive_partial_update
|
||||
description: ''
|
||||
parameters:
|
||||
- name: data
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
tags:
|
||||
- todo
|
||||
delete:
|
||||
operationId: todo_recursive_delete
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
tags:
|
||||
- todo
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: A unique integer value identifying this todo tree.
|
||||
required: true
|
||||
type: integer
|
||||
/todo/tree/:
|
||||
get:
|
||||
operationId: todo_tree_list
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/TodoTree'
|
||||
tags:
|
||||
- todo
|
||||
parameters: []
|
||||
/todo/tree/{id}/:
|
||||
get:
|
||||
operationId: todo_tree_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoTree'
|
||||
tags:
|
||||
- todo
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: A unique integer value identifying this todo tree.
|
||||
required: true
|
||||
type: integer
|
||||
/todo/yetanother/:
|
||||
get:
|
||||
operationId: todo_yetanother_list
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/TodoYetAnother'
|
||||
tags:
|
||||
- todo
|
||||
parameters: []
|
||||
/todo/yetanother/{id}/:
|
||||
get:
|
||||
operationId: todo_yetanother_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoYetAnother'
|
||||
tags:
|
||||
- todo
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: A unique integer value identifying this todo yet another.
|
||||
required: true
|
||||
type: integer
|
||||
/todo/{id}/:
|
||||
get:
|
||||
operationId: todo_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/Todo'
|
||||
tags:
|
||||
- todo
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: A unique integer value identifying this todo.
|
||||
required: true
|
||||
type: integer
|
||||
/todo/{todo_id}/yetanothers/{yetanother_id}/:
|
||||
get:
|
||||
operationId: todo_yetanothers_read
|
||||
description: ''
|
||||
parameters: []
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/TodoYetAnother'
|
||||
tags:
|
||||
- todo
|
||||
parameters:
|
||||
- name: todo_id
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
- name: yetanother_id
|
||||
in: path
|
||||
required: true
|
||||
type: string
|
||||
/users/:
|
||||
get:
|
||||
operationId: users_list
|
||||
@@ -359,6 +726,7 @@ paths:
|
||||
description: this field is generated from a query_serializer
|
||||
required: false
|
||||
type: string
|
||||
minLength: 1
|
||||
- name: is_staff
|
||||
in: query
|
||||
description: this one too!
|
||||
@@ -371,8 +739,6 @@ paths:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/UserSerializerrr'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- users
|
||||
post:
|
||||
@@ -399,10 +765,9 @@ paths:
|
||||
properties:
|
||||
username:
|
||||
type: string
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- users
|
||||
security: []
|
||||
patch:
|
||||
operationId: users_dummy
|
||||
description: dummy operation
|
||||
@@ -410,8 +775,6 @@ paths:
|
||||
responses:
|
||||
'200':
|
||||
description: ''
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- users
|
||||
parameters: []
|
||||
@@ -429,8 +792,6 @@ paths:
|
||||
description: response description
|
||||
schema:
|
||||
$ref: '#/definitions/UserSerializerrr'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- users
|
||||
put:
|
||||
@@ -447,8 +808,6 @@ paths:
|
||||
description: ''
|
||||
schema:
|
||||
$ref: '#/definitions/UserSerializerrr'
|
||||
consumes:
|
||||
- application/json
|
||||
tags:
|
||||
- users
|
||||
parameters:
|
||||
@@ -461,12 +820,14 @@ definitions:
|
||||
required:
|
||||
- title
|
||||
- body
|
||||
- group
|
||||
type: object
|
||||
properties:
|
||||
title:
|
||||
description: title model help_text
|
||||
type: string
|
||||
maxLength: 255
|
||||
minLength: 1
|
||||
author:
|
||||
description: The ID of the user that created this article; if none is provided,
|
||||
defaults to the currently logged in user.
|
||||
@@ -476,6 +837,7 @@ definitions:
|
||||
description: body serializer help_text
|
||||
type: string
|
||||
maxLength: 5000
|
||||
minLength: 1
|
||||
slug:
|
||||
description: slug model help_text
|
||||
type: string
|
||||
@@ -497,6 +859,7 @@ definitions:
|
||||
description: but i needed to test these 2 fields somehow
|
||||
type: string
|
||||
format: uri
|
||||
minLength: 1
|
||||
readOnly: true
|
||||
uuid:
|
||||
description: should articles have UUIDs?
|
||||
@@ -510,6 +873,53 @@ definitions:
|
||||
cover_name:
|
||||
type: string
|
||||
readOnly: true
|
||||
article_type:
|
||||
description: IntegerField declared on model with choices=(...) and exposed
|
||||
via ModelSerializer
|
||||
type: integer
|
||||
enum:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
- 7
|
||||
- 8
|
||||
group:
|
||||
type: string
|
||||
format: uuid
|
||||
original_group:
|
||||
type: string
|
||||
format: uuid
|
||||
readOnly: true
|
||||
Identity:
|
||||
title: Identity
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
firstName:
|
||||
title: FirstName
|
||||
type: string
|
||||
maxLength: 30
|
||||
minLength: 1
|
||||
lastName:
|
||||
title: LastName
|
||||
description: <strong>Here's some HTML!</strong>
|
||||
type: string
|
||||
maxLength: 30
|
||||
minLength: 1
|
||||
Person:
|
||||
required:
|
||||
- identity
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
identity:
|
||||
$ref: '#/definitions/Identity'
|
||||
Project:
|
||||
required:
|
||||
- projectName
|
||||
@@ -520,10 +930,12 @@ definitions:
|
||||
title: Project name
|
||||
description: Name of the project
|
||||
type: string
|
||||
minLength: 1
|
||||
githubRepo:
|
||||
title: Github repo
|
||||
description: Github repository of the project
|
||||
type: string
|
||||
minLength: 1
|
||||
Snippet:
|
||||
required:
|
||||
- code
|
||||
@@ -545,6 +957,7 @@ definitions:
|
||||
description: The ID of the user that created this snippet.
|
||||
type: string
|
||||
readOnly: true
|
||||
minLength: 1
|
||||
title: Owner as string
|
||||
title:
|
||||
title: Title
|
||||
@@ -553,11 +966,11 @@ definitions:
|
||||
code:
|
||||
title: Code
|
||||
type: string
|
||||
minLength: 1
|
||||
linenos:
|
||||
title: Linenos
|
||||
type: boolean
|
||||
language:
|
||||
title: Language
|
||||
description: Sample help text for language
|
||||
type: object
|
||||
properties:
|
||||
@@ -1002,7 +1415,6 @@ definitions:
|
||||
- zephir
|
||||
default: python
|
||||
styles:
|
||||
title: Styles
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
@@ -1039,12 +1451,10 @@ definitions:
|
||||
default:
|
||||
- friendly
|
||||
lines:
|
||||
title: Lines
|
||||
type: array
|
||||
items:
|
||||
type: integer
|
||||
exampleProjects:
|
||||
title: Example projects
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Project'
|
||||
@@ -1055,6 +1465,123 @@ definitions:
|
||||
type: number
|
||||
readOnly: true
|
||||
default: 6.9
|
||||
rateAsString:
|
||||
title: Rate as string
|
||||
type: string
|
||||
format: decimal
|
||||
default: '0.000'
|
||||
rate:
|
||||
title: Rate
|
||||
type: number
|
||||
format: decimal
|
||||
default: 0.0
|
||||
minimum: 0.0
|
||||
Todo:
|
||||
required:
|
||||
- title
|
||||
type: object
|
||||
properties:
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
TodoAnother:
|
||||
required:
|
||||
- title
|
||||
- todo
|
||||
type: object
|
||||
properties:
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
todo:
|
||||
$ref: '#/definitions/Todo'
|
||||
TodoRecursive:
|
||||
required:
|
||||
- title
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
parent:
|
||||
$ref: '#/definitions/TodoRecursive'
|
||||
parent_id:
|
||||
type: integer
|
||||
title: Parent id
|
||||
TodoTree:
|
||||
required:
|
||||
- title
|
||||
- children
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
children:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/TodoTree'
|
||||
TodoYetAnother:
|
||||
required:
|
||||
- title
|
||||
type: object
|
||||
properties:
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
todo:
|
||||
required:
|
||||
- title
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
todo:
|
||||
required:
|
||||
- title
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 50
|
||||
minLength: 1
|
||||
readOnly: true
|
||||
readOnly: true
|
||||
example:
|
||||
title: parent
|
||||
todo:
|
||||
title: child
|
||||
todo: null
|
||||
UserSerializerrr:
|
||||
required:
|
||||
- username
|
||||
@@ -1073,19 +1600,18 @@ definitions:
|
||||
type: string
|
||||
pattern: ^[\w.@+-]+$
|
||||
maxLength: 150
|
||||
minLength: 1
|
||||
email:
|
||||
title: Email address
|
||||
type: string
|
||||
format: email
|
||||
maxLength: 254
|
||||
articles:
|
||||
title: Articles
|
||||
type: array
|
||||
items:
|
||||
type: integer
|
||||
uniqueItems: true
|
||||
snippets:
|
||||
title: Snippets
|
||||
type: array
|
||||
items:
|
||||
type: integer
|
||||
@@ -1096,6 +1622,7 @@ definitions:
|
||||
type: string
|
||||
format: ipv4
|
||||
readOnly: true
|
||||
minLength: 1
|
||||
last_connected_at:
|
||||
title: Last connected at
|
||||
description: really?
|
||||
@@ -1103,7 +1630,6 @@ definitions:
|
||||
format: date
|
||||
readOnly: true
|
||||
article_slugs:
|
||||
title: Article slugs
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
@@ -1111,6 +1637,3 @@ definitions:
|
||||
pattern: ^[-a-zA-Z0-9_]+$
|
||||
readOnly: true
|
||||
uniqueItems: true
|
||||
securityDefinitions:
|
||||
basic:
|
||||
type: basic
|
||||
|
||||
+17
-17
@@ -9,24 +9,13 @@ from collections import OrderedDict
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management import call_command
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.codecs import yaml_sane_load
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
|
||||
|
||||
def call_generate_swagger(output_file='-', overwrite=False, format='', api_url='',
|
||||
mock=False, user='', private=False, **kwargs):
|
||||
out = StringIO()
|
||||
call_command(
|
||||
'generate_swagger', stdout=out,
|
||||
output_file=output_file, overwrite=overwrite, format=format,
|
||||
api_url=api_url, mock=mock, user=user, private=private,
|
||||
**kwargs
|
||||
)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def test_reference_schema(db, reference_schema):
|
||||
def test_reference_schema(call_generate_swagger, db, reference_schema):
|
||||
User.objects.create_superuser('admin', 'admin@admin.admin', 'blabla')
|
||||
|
||||
output = call_generate_swagger(format='yaml', api_url='http://test.local:8002/', user='admin')
|
||||
@@ -34,18 +23,29 @@ def test_reference_schema(db, reference_schema):
|
||||
assert output_schema == reference_schema
|
||||
|
||||
|
||||
def test_non_public(db):
|
||||
def test_non_public(call_generate_swagger, db):
|
||||
output = call_generate_swagger(format='yaml', api_url='http://test.local:8002/', private=True)
|
||||
output_schema = yaml_sane_load(output)
|
||||
assert len(output_schema['paths']) == 0
|
||||
|
||||
|
||||
def test_no_mock(db):
|
||||
def test_no_mock(call_generate_swagger, db):
|
||||
output = call_generate_swagger()
|
||||
output_schema = json.loads(output, object_pairs_hook=OrderedDict)
|
||||
assert len(output_schema['paths']) > 0
|
||||
|
||||
|
||||
class EmptySchemaGenerator(OpenAPISchemaGenerator):
|
||||
def get_paths(self, endpoints, components, request, public):
|
||||
return openapi.Paths(paths={}), ''
|
||||
|
||||
|
||||
def test_generator_class(call_generate_swagger, db):
|
||||
output = call_generate_swagger(generator_class_name='test_management.EmptySchemaGenerator')
|
||||
output_schema = json.loads(output, object_pairs_hook=OrderedDict)
|
||||
assert len(output_schema['paths']) == 0
|
||||
|
||||
|
||||
def silentremove(filename):
|
||||
try:
|
||||
os.remove(filename)
|
||||
@@ -53,7 +53,7 @@ def silentremove(filename):
|
||||
pass
|
||||
|
||||
|
||||
def test_file_output(db):
|
||||
def test_file_output(call_generate_swagger, db):
|
||||
prefix = os.path.join(tempfile.gettempdir(), tempfile.gettempprefix())
|
||||
name = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
|
||||
yaml_file = prefix + name + '.yaml'
|
||||
|
||||
@@ -46,3 +46,9 @@ def test_noop_inspectors(swagger_settings, mock_schema_request, codec_json, refe
|
||||
json_bytes = codec_json.encode(swagger)
|
||||
swagger_dict = json.loads(json_bytes.decode('utf-8'), object_pairs_hook=OrderedDict)
|
||||
compare_schemas(swagger_dict, reference_schema)
|
||||
|
||||
|
||||
def test_no_nested_model(swagger_dict):
|
||||
# ForeignKey models in deep ModelViewSets might wrongly be labeled as 'Nested' in the definitions section
|
||||
# see https://github.com/axnsan12/drf-yasg/issues/59
|
||||
assert 'Nested' not in swagger_dict['definitions']
|
||||
|
||||
@@ -2,10 +2,16 @@ import json
|
||||
from collections import OrderedDict
|
||||
|
||||
import pytest
|
||||
from django.conf.urls import url
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
|
||||
from drf_yasg import codecs, openapi
|
||||
from drf_yasg.codecs import yaml_sane_load
|
||||
from drf_yasg.errors import SwaggerGenerationError
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
|
||||
|
||||
def test_schema_is_valid(swagger, codec_yaml):
|
||||
@@ -46,14 +52,98 @@ def test_yaml_and_json_match(codec_yaml, codec_json, swagger):
|
||||
|
||||
|
||||
def test_basepath_only(mock_schema_request):
|
||||
with pytest.raises(SwaggerGenerationError):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='/basepath/',
|
||||
)
|
||||
|
||||
generator.get_schema(mock_schema_request, public=True)
|
||||
|
||||
|
||||
def test_no_netloc(mock_schema_request):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='/basepath/',
|
||||
url='',
|
||||
)
|
||||
|
||||
swagger = generator.get_schema(mock_schema_request, public=True)
|
||||
assert 'host' not in swagger
|
||||
assert 'schemes' not in swagger
|
||||
assert swagger['basePath'] == '/' # base path is not implemented for now
|
||||
assert 'host' not in swagger and 'schemes' not in swagger
|
||||
assert swagger['info']['version'] == 'v2'
|
||||
|
||||
|
||||
def test_securiy_requirements(swagger_settings, mock_schema_request):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='',
|
||||
)
|
||||
swagger_settings['SECURITY_REQUIREMENTS'] = []
|
||||
|
||||
swagger = generator.get_schema(mock_schema_request, public=True)
|
||||
assert swagger['security'] == []
|
||||
|
||||
|
||||
def test_replaced_serializer():
|
||||
class DetailSerializer(serializers.Serializer):
|
||||
detail = serializers.CharField()
|
||||
|
||||
class DetailViewSet(viewsets.ViewSet):
|
||||
serializer_class = DetailSerializer
|
||||
|
||||
@swagger_auto_schema(responses={404: openapi.Response("Not found or Not accessible", DetailSerializer)})
|
||||
def retrieve(self, request, pk=None):
|
||||
serializer = DetailSerializer({'detail': None})
|
||||
return Response(serializer.data)
|
||||
|
||||
router = routers.DefaultRouter()
|
||||
router.register(r'details', DetailViewSet, base_name='details')
|
||||
|
||||
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)
|
||||
assert 'Detail' in swagger['definitions']
|
||||
assert 'detail' in swagger['definitions']['Detail']['properties']
|
||||
responses = swagger['paths']['/details/{id}/']['get']['responses']
|
||||
assert '404' in responses
|
||||
assert responses['404']['schema']['$ref'] == "#/definitions/Detail"
|
||||
|
||||
|
||||
def test_url_order():
|
||||
# this view with description override should show up in the schema ...
|
||||
@swagger_auto_schema(method='get', operation_description="description override")
|
||||
@api_view()
|
||||
def test_override(request, pk=None):
|
||||
return Response({"message": "Hello, world!"})
|
||||
|
||||
# ... instead of this view which appears later in the url patterns
|
||||
@api_view()
|
||||
def test_view(request, pk=None):
|
||||
return Response({"message": "Hello, world!"})
|
||||
|
||||
patterns = [
|
||||
url(r'^/test/$', test_override),
|
||||
url(r'^/test/$', test_view),
|
||||
]
|
||||
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='',
|
||||
patterns=patterns
|
||||
)
|
||||
|
||||
# description override is successful
|
||||
swagger = generator.get_schema(None, True)
|
||||
assert swagger['paths']['/test/']['get']['description'] == 'description override'
|
||||
|
||||
# get_endpoints only includes one endpoint
|
||||
assert len(generator.get_endpoints(None)['/test/'][1]) == 1
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
from collections import OrderedDict
|
||||
from random import shuffle
|
||||
|
||||
from drf_yasg import openapi
|
||||
|
||||
|
||||
@@ -51,3 +54,15 @@ def test_trailing_underscore_stripped():
|
||||
del sd.in_
|
||||
assert 'in' not in sd
|
||||
assert not hasattr(sd, 'in__')
|
||||
|
||||
|
||||
def test_extra_ordering():
|
||||
"""Insertion order should also be consistent when setting undeclared parameters (kwargs) in SwaggerDict"""
|
||||
extras = [('beta', 1), ('alpha', 2), ('omega', 3), ('gamma', 4)]
|
||||
shuffled_extras = list(extras)
|
||||
shuffle(shuffled_extras)
|
||||
|
||||
s1 = openapi.SwaggerDict(**OrderedDict(extras))
|
||||
s2 = openapi.SwaggerDict(**OrderedDict(shuffled_extras))
|
||||
|
||||
assert list(s1.items()) == list(s2.items())
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user