Compare commits
62 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d1150f1ab | |||
| bc4037f721 | |||
| 6c4dcb18bb | |||
| 4445137d55 | |||
| 57870d12a4 | |||
| 7a3fe8ec0c | |||
| 757d47e1c0 | |||
| 59a51ba4a7 | |||
| 55223e32e2 | |||
| 6a478e14d7 | |||
| 57d77cc48a | |||
| c225f66fb7 | |||
| 47de6f2f6f | |||
| 8dbf3fe984 | |||
| 1c3fba6e54 | |||
| c4379dc6a7 | |||
| 6b38a3b6c1 | |||
| 464a518ae5 | |||
| 15c67891c6 | |||
| 917ccd1f56 | |||
| fd099998ea | |||
| a6e24e20c3 | |||
| 6608e0050c | |||
| 68b0dda0b9 | |||
| f81795d745 | |||
| caa397b906 | |||
| faf81e7b6d | |||
| 74fcd47047 | |||
| 02b72c466e | |||
| 10deea826d | |||
| bbdc37a45e | |||
| eba228a114 | |||
| ee4789776a | |||
| 22853b87c7 | |||
| d39764d383 | |||
| 60e266fe99 | |||
| 1f190744cd | |||
| 9f14114520 | |||
| c85acee405 | |||
| 1aaec6b3e5 | |||
| c89f96fcb0 | |||
| 73adc49b2c | |||
| 313d122004 | |||
| 443d74b636 | |||
| 43034ddc4b | |||
| 9f6ee4da87 | |||
| f05889292a | |||
| 8a8a9faeeb | |||
| 7683a28816 | |||
| 260a994baf | |||
| 6060192a89 | |||
| 06a461ec09 | |||
| cae07f3eaf | |||
| 16b697b40d | |||
| 8a0d5a964d | |||
| 521172c195 | |||
| f6c30181fe | |||
| da4b7d4e74 | |||
| 6346d855cf | |||
| 53593af36f | |||
| 738326ac43 | |||
| 8a5be407e2 |
+3
-2
@@ -11,14 +11,15 @@ coverage:
|
||||
default:
|
||||
enabled: yes
|
||||
target: auto
|
||||
threshold: 100%
|
||||
if_no_uploads: error
|
||||
if_ci_failed: error
|
||||
|
||||
patch:
|
||||
default:
|
||||
enabled: yes
|
||||
target: 80%
|
||||
threshold: 60%
|
||||
target: 100%
|
||||
threshold: 100%
|
||||
if_no_uploads: error
|
||||
if_ci_failed: error
|
||||
|
||||
|
||||
+10
-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
|
||||
@@ -14,9 +16,15 @@ exclude_lines =
|
||||
|
||||
# Don't complain if tests don't hit defensive assertion code:
|
||||
raise AssertionError
|
||||
raise ImproperlyConfigured
|
||||
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:
|
||||
if 0:
|
||||
@@ -26,7 +34,8 @@ exclude_lines =
|
||||
raise SwaggerGenerationError
|
||||
|
||||
ignore_errors = True
|
||||
precision = 0
|
||||
precision = 2
|
||||
show_missing = True
|
||||
|
||||
[paths]
|
||||
source =
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
* text=auto
|
||||
*.sh text eol=lf
|
||||
@@ -1,4 +1,7 @@
|
||||
node_modules/
|
||||
testproj/db.sqlite3
|
||||
testproj/staticfiles
|
||||
.vscode/
|
||||
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Python template
|
||||
|
||||
Generated
+2
-2
@@ -4,7 +4,7 @@
|
||||
<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" />
|
||||
@@ -32,4 +32,4 @@
|
||||
<option name="projectConfiguration" value="py.test" />
|
||||
<option name="PROJECT_TEST_RUNNER" value="py.test" />
|
||||
</component>
|
||||
</module>
|
||||
</module>
|
||||
|
||||
+49
-12
@@ -1,42 +1,79 @@
|
||||
language: python
|
||||
cache: pip
|
||||
|
||||
python:
|
||||
- '2.7'
|
||||
- '3.4'
|
||||
- '3.5'
|
||||
- '3.6'
|
||||
- '3.7-dev'
|
||||
|
||||
env:
|
||||
- DRF=3.7
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
jobs:
|
||||
include:
|
||||
- python: '3.5'
|
||||
env: TOXENV=docs
|
||||
- python: '2.7'
|
||||
env: TOXENV=flake8
|
||||
- python: '3.6'
|
||||
- stage: test
|
||||
python: '3.6'
|
||||
env: DRF=master
|
||||
-
|
||||
python: '3.5'
|
||||
env: TOXENV=docs
|
||||
-
|
||||
python: '2.7'
|
||||
env: TOXENV=lint
|
||||
|
||||
- stage: publish
|
||||
python: '3.6'
|
||||
script: skip
|
||||
env: PYPI_DEPLOY=true
|
||||
deploy: &pypi
|
||||
provider: pypi
|
||||
user: cvijdea
|
||||
password:
|
||||
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 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:
|
||||
- tox
|
||||
- 'if [[ "$USE_DETOX" == "yes" ]]; then detox; else tox; fi'
|
||||
|
||||
after_success:
|
||||
- codecov
|
||||
- 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
|
||||
|
||||
+50
-16
@@ -27,43 +27,55 @@ Pull requests
|
||||
|
||||
You want to contribute some code? Great! Here are a few steps to get you started:
|
||||
|
||||
#. Fork the repository on GitHub
|
||||
#. Clone your fork and create a branch for the code you want to add
|
||||
#. Create a new virtualenv and install the package in development mode
|
||||
#. **Fork the repository on GitHub**
|
||||
#. **Clone your fork and create a branch for the code you want to add**
|
||||
#. **Create a new virtualenv and install the package in development mode**
|
||||
|
||||
.. code:: console
|
||||
|
||||
$ virtualenv venv
|
||||
$ source venv/bin/activate
|
||||
(venv) $ pip install -e .[validation]
|
||||
(venv) $ pip install -rrequirements/dev.txt -rrequirements/test.txt
|
||||
(venv) $ pip install -rrequirements/dev.txt "Django>=1.11.7"
|
||||
|
||||
#. Make your changes and check them against the test project
|
||||
#. **Make your changes and check them against the test project**
|
||||
|
||||
.. code:: console
|
||||
|
||||
(venv) $ cd testproj
|
||||
(venv) $ python manage.py migrate
|
||||
(venv) $ python manage.py shell -c "import createsuperuser"
|
||||
(venv) $ python manage.py runserver
|
||||
(venv) $ curl localhost:8000/swagger.yaml
|
||||
(venv) $ firefox localhost:8000/swagger/
|
||||
|
||||
#. Update the tests if necessary
|
||||
#. **Update the tests if necessary**
|
||||
|
||||
You can find them in the ``tests`` directory.
|
||||
|
||||
If your change modifies the expected schema output, you should download the new generated ``swagger.yaml``, diff it
|
||||
against the old reference output in ``tests/reference.yaml``, and replace it after checking that no unexpected
|
||||
changes appeared.
|
||||
|
||||
#. Run tests. The project is setup to use tox and pytest for testing
|
||||
If your change modifies the expected schema output, you should regenerate the reference schema at
|
||||
``tests/reference.yaml``:
|
||||
|
||||
.. code:: console
|
||||
|
||||
(venv) $ cd testproj
|
||||
(venv) $ python manage.py generate_swagger ../tests/reference.yaml --overwrite --user admin --url http://test.local:8002/
|
||||
|
||||
After checking the git diff to verify that no unexpected changes appeared, you should commit the new
|
||||
``reference.yaml`` together with your changes.
|
||||
|
||||
#. **Run tests. The project is setup to use tox and pytest for testing**
|
||||
|
||||
.. code:: console
|
||||
|
||||
# (optional) sort imports with isort and check flake8 linting
|
||||
(venv) $ isort --apply
|
||||
(venv) $ flake8 src/drf_yasg testproj tests setup.py
|
||||
# run tests in the current environment, faster than tox
|
||||
(venv) $ pytest --cov
|
||||
# (optional) run tests for other python versions in separate environments
|
||||
(venv) $ tox
|
||||
|
||||
#. Update documentation
|
||||
#. **Update documentation**
|
||||
|
||||
If the change modifies behaviour or adds new features, you should update the documentation and ``README.rst``
|
||||
accordingly. Documentation is written in reStructuredText and built using Sphinx. You can find the sources in the
|
||||
@@ -75,10 +87,32 @@ You want to contribute some code? Great! Here are a few steps to get you started
|
||||
|
||||
(venv) $ tox -e docs
|
||||
|
||||
#. Push your branch and submit a pull request to the master branch on GitHub
|
||||
#. **Push your branch and submit a pull request to the master branch on GitHub**
|
||||
|
||||
Incomplete/Work In Progress pull requests are encouraged, because they allow you to get feedback and help more
|
||||
easily.
|
||||
|
||||
#. Your code must pass all the required travis jobs before it is merged. As of now, this includes running on
|
||||
Python 2.7, 3.4, 3.5 and 3.6, and building the docs succesfully.
|
||||
#. **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 latest tag
|
||||
* commit & tag the release
|
||||
* 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
|
||||
.. _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
|
||||
|
||||
@@ -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 -
|
||||
+153
-85
@@ -15,26 +15,37 @@ Compatible with
|
||||
- **Django**: 1.11, 2.0
|
||||
- **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
|
||||
|
||||
+ ``URLPathVersioning`` and ``NamespaceVersioning`` are supported
|
||||
+ ``HostnameVersioning``, ``AcceptHeaderVersioning`` and ``QueryParameterVersioning`` are not currently supported
|
||||
|
||||
.. figure:: https://raw.githubusercontent.com/axnsan12/drf-yasg/1.0.2/screenshots/redoc-nested-response.png
|
||||
:width: 100%
|
||||
@@ -94,42 +105,42 @@ In ``settings.py``:
|
||||
|
||||
.. code:: python
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'drf_yasg',
|
||||
...
|
||||
]
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'drf_yasg',
|
||||
...
|
||||
]
|
||||
|
||||
In ``urls.py``:
|
||||
|
||||
.. code:: python
|
||||
|
||||
...
|
||||
from drf_yasg.views import get_schema_view
|
||||
from drf_yasg import openapi
|
||||
...
|
||||
from drf_yasg.views import get_schema_view
|
||||
from drf_yasg import openapi
|
||||
|
||||
...
|
||||
...
|
||||
|
||||
schema_view = get_schema_view(
|
||||
openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
description="Test description",
|
||||
terms_of_service="https://www.google.com/policies/terms/",
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
),
|
||||
validators=['ssv', 'flex'],
|
||||
public=True,
|
||||
permission_classes=(permissions.AllowAny,),
|
||||
)
|
||||
schema_view = get_schema_view(
|
||||
openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
description="Test description",
|
||||
terms_of_service="https://www.google.com/policies/terms/",
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
),
|
||||
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'),
|
||||
...
|
||||
]
|
||||
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'),
|
||||
...
|
||||
]
|
||||
|
||||
This exposes 4 cached, validated and publicly available endpoints:
|
||||
|
||||
@@ -141,18 +152,21 @@ This exposes 4 cached, validated and publicly available endpoints:
|
||||
2. Configuration
|
||||
================
|
||||
|
||||
---------------------------------
|
||||
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
|
||||
|
||||
-------------------------------
|
||||
b. ``SchemaView`` options
|
||||
-------------------------------
|
||||
|
||||
@@ -164,11 +178,11 @@ 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``
|
||||
----------------------------------------------
|
||||
|
||||
@@ -177,42 +191,67 @@ The possible settings and their default values are as follows:
|
||||
|
||||
.. code:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'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_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',
|
||||
],
|
||||
|
||||
# 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'
|
||||
}
|
||||
},
|
||||
# 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': None,
|
||||
|
||||
# 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': '',
|
||||
'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-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': 2,
|
||||
}
|
||||
# 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,
|
||||
}
|
||||
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
|
||||
==========
|
||||
@@ -223,16 +262,16 @@ caching the schema view in-memory, with some sane defaults:
|
||||
* caching is enabled by the `cache_page <https://docs.djangoproject.com/en/1.11/topics/cache/#the-per-view-cache>`__
|
||||
decorator, using the default Django cache backend, can be changed using the ``cache_kwargs`` argument
|
||||
* HTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemas
|
||||
* if `public` is set to ``False`` on the SchemaView, the cached schema varies on the ``Cookie`` and ``Authorization``
|
||||
HTTP headers to enable filtering of visible endpoints according to the authentication credentials of each user; note
|
||||
that this means that every user accessing the schema will have a separate schema cached in memory.
|
||||
* the cached schema varies on the ``Cookie`` and ``Authorization`` HTTP headers to enable filtering of visible endpoints
|
||||
according to the authentication credentials of each user; note that this means that every user accessing the schema
|
||||
will have a separate schema cached in memory.
|
||||
|
||||
4. Validation
|
||||
=============
|
||||
|
||||
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.
|
||||
@@ -241,6 +280,7 @@ Caching can mitigate the speed impact of validation.
|
||||
The provided validation will catch syntactic errors, but more subtle violations of the spec might slip by them. To
|
||||
ensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods:
|
||||
|
||||
-------------------------------
|
||||
``swagger-ui`` validation badge
|
||||
-------------------------------
|
||||
|
||||
@@ -271,6 +311,7 @@ If your schema is not accessible from the internet, you can run a local copy of
|
||||
$ curl http://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi
|
||||
{}
|
||||
|
||||
---------------------
|
||||
Using ``swagger-cli``
|
||||
---------------------
|
||||
|
||||
@@ -283,6 +324,7 @@ https://www.npmjs.com/package/swagger-cli
|
||||
$ swagger-cli validate http://test.local:8002/swagger.yaml
|
||||
http://test.local:8002/swagger.yaml is valid
|
||||
|
||||
--------------------------------------------------------------
|
||||
Manually on `editor.swagger.io <https://editor.swagger.io/>`__
|
||||
--------------------------------------------------------------
|
||||
|
||||
@@ -303,6 +345,26 @@ You can use the specification outputted by this library together with
|
||||
|
||||
See the github page linked above for more details.
|
||||
|
||||
.. _readme-testproj:
|
||||
|
||||
6. Example project
|
||||
==================
|
||||
|
||||
For additional usage examples, you can take a look at the test project in the ``testproj`` directory:
|
||||
|
||||
.. code:: console
|
||||
|
||||
$ git clone https://github.com/axnsan12/drf-yasg.git
|
||||
$ cd drf-yasg
|
||||
$ virtualenv venv
|
||||
$ source venv/bin/activate
|
||||
(venv) $ cd testproj
|
||||
(venv) $ pip install -r requirements.txt
|
||||
(venv) $ python manage.py migrate
|
||||
(venv) $ python manage.py shell -c "import createsuperuser"
|
||||
(venv) $ python manage.py runserver
|
||||
(venv) $ firefox localhost:8000/swagger/
|
||||
|
||||
**********
|
||||
Background
|
||||
**********
|
||||
@@ -345,10 +407,16 @@ named schemas.
|
||||
|
||||
Both projects are also currently unmantained.
|
||||
|
||||
Documentation, advanced usage
|
||||
=============================
|
||||
************************
|
||||
Third-party integrations
|
||||
************************
|
||||
|
||||
https://drf-yasg.readthedocs.io/en/latest/
|
||||
djangorestframework-camel-case
|
||||
===============================
|
||||
|
||||
Integration with `djangorestframework-camel-case <https://github.com/vbabiy/djangorestframework-camel-case>`_ is
|
||||
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.
|
||||
|
||||
.. |travis| image:: https://img.shields.io/travis/axnsan12/drf-yasg/master.svg
|
||||
:target: https://travis-ci.org/axnsan12/drf-yasg
|
||||
@@ -359,7 +427,7 @@ https://drf-yasg.readthedocs.io/en/latest/
|
||||
:alt: Codecov
|
||||
|
||||
.. |pypi-version| image:: https://img.shields.io/pypi/v/drf-yasg.svg
|
||||
:target: https://pypi.org/project/drf-yasg/
|
||||
:target: https://pypi.python.org/pypi/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": "/"
|
||||
}
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
.versionadded, .versionchanged, .deprecated {
|
||||
font-family: "Roboto", Corbel, Avenir, "Lucida Grande", "Lucida Sans", sans-serif;
|
||||
padding: 10px 13px;
|
||||
border: 1px solid rgb(137, 191, 4);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.versionmodified {
|
||||
font-weight: bold;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.versionadded p, .versionchanged p, .deprecated p,
|
||||
/*override fucking !important by being more specific */
|
||||
.rst-content dl .versionadded p, .rst-content dl .versionchanged p {
|
||||
margin: 0 !important;
|
||||
}
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{% extends "!layout.html" %}
|
||||
{% block extrahead %}
|
||||
<meta name="google-site-verification" content="saewLzcrUS1lAAgNVIikKWc3DUbFcE-TWtpyw3AW8CA" />
|
||||
{% endblock %}
|
||||
+80
-4
@@ -2,21 +2,97 @@
|
||||
Changelog
|
||||
#########
|
||||
|
||||
*********
|
||||
**1.2.1**
|
||||
*********
|
||||
|
||||
- Fixed deployment issues
|
||||
|
||||
*********
|
||||
**1.2.0**
|
||||
*********
|
||||
|
||||
- **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**
|
||||
*********
|
||||
|
||||
- **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
|
||||
|
||||
*********
|
||||
**1.1.2**
|
||||
*********
|
||||
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.8.1
|
||||
- **IMPROVED:** removed some unneeded static files
|
||||
|
||||
*********
|
||||
**1.1.1**
|
||||
*********
|
||||
|
||||
- **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 ``$``
|
||||
|
||||
*********
|
||||
**1.1.0**
|
||||
*********
|
||||
|
||||
- **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>`
|
||||
- **ADDED:** added ``operation_id`` parameter to :func:`@swagger_auto_schema <.swagger_auto_schema>`
|
||||
- **ADDED:** integration with `djangorestframework-camel-case
|
||||
<https://github.com/vbabiy/djangorestframework-camel-case>`_ (:issue:`28`)
|
||||
- **IMPROVED:** strings, arrays and integers will now have min/max validation attributes inferred from the
|
||||
field-level validators
|
||||
- **FIXED:** fixed a bug that caused ``title`` to never be generated for Schemas; ``title`` is now correctly
|
||||
populated from the field's ``label`` property
|
||||
|
||||
*********
|
||||
**1.0.6**
|
||||
*********
|
||||
|
||||
- **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
|
||||
- **IMPROVED:** ``PrimaryKeyRelatedField`` and ``SlugRelatedField`` will now have
|
||||
appropriate types based on the related model (:pr:`26`)
|
||||
- **IMPROVED:** mock views will now have a bound request even with ``public=False`` (:pr:`23`)
|
||||
|
||||
*********
|
||||
**1.0.5**
|
||||
*********
|
||||
|
||||
- **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>`_
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.7.0
|
||||
- **IMPROVED:** ``FileField`` is now generated as an URL or file name in response Schemas
|
||||
(:pr:`21`, thanks to :ghuser:`h-hirokawa`)
|
||||
|
||||
*********
|
||||
**1.0.4**
|
||||
*********
|
||||
|
||||
- **FIX:** fixed improper generation of YAML references
|
||||
- **FEATURE:** added ``query_serializer`` parameter to
|
||||
- **FIXED:** fixed improper generation of YAML references
|
||||
- **ADDED:** added ``query_serializer`` parameter to
|
||||
:func:`@swagger_auto_schema <.swagger_auto_schema>` (:issue:`16`, :pr:`17`)
|
||||
|
||||
*********
|
||||
**1.0.3**
|
||||
*********
|
||||
|
||||
- **FIX:** fixed bug that caused schema views returned from cache to fail (:issue:`14`)
|
||||
- **FIX:** disabled automatic generation of response schemas for form operations to avoid confusing errors caused by
|
||||
- **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
|
||||
|
||||
*********
|
||||
|
||||
+81
-21
@@ -3,7 +3,9 @@
|
||||
#
|
||||
# drf-yasg documentation build configuration file, created by
|
||||
# sphinx-quickstart on Sun Dec 10 15:20:34 2017.
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import sphinx_rtd_theme
|
||||
@@ -67,9 +69,6 @@ pygments_style = 'sphinx'
|
||||
|
||||
modindex_common_prefix = ['drf_yasg.']
|
||||
|
||||
# If true, `todo` and `todoList` produce output, else they produce nothing.
|
||||
todo_include_todos = False
|
||||
|
||||
# -- Options for HTML output ----------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
@@ -168,6 +167,7 @@ nitpick_ignore = [
|
||||
|
||||
('py:class', 'ruamel.yaml.dumper.SafeDumper'),
|
||||
('py:class', 'rest_framework.renderers.BaseRenderer'),
|
||||
('py:class', 'rest_framework.schemas.generators.EndpointEnumerator'),
|
||||
('py:class', 'rest_framework.views.APIView'),
|
||||
|
||||
('py:class', 'OpenAPICodecYaml'),
|
||||
@@ -184,15 +184,18 @@ nitpick_ignore = [
|
||||
('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'),
|
||||
]
|
||||
|
||||
@@ -202,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
|
||||
|
||||
@@ -213,42 +216,99 @@ import drf_yasg.views # noqa: E402
|
||||
|
||||
drf_yasg.views.SchemaView = drf_yasg.views.get_schema_view(None)
|
||||
|
||||
# monkey patch to stop sphinx from trying to find classes by their real location instead of the
|
||||
# top-level __init__ alias; this allows us to document only `drf_yasg.inspectors` and avoid broken references or
|
||||
# double documenting
|
||||
|
||||
import drf_yasg.inspectors # noqa: E402
|
||||
|
||||
|
||||
def redirect_cls(cls):
|
||||
if cls.__module__.startswith('drf_yasg.inspectors'):
|
||||
return getattr(drf_yasg.inspectors, cls.__name__)
|
||||
return cls
|
||||
|
||||
|
||||
for cls_name in drf_yasg.inspectors.__all__:
|
||||
# first pass - replace all classes' module with the top level module
|
||||
real_cls = getattr(drf_yasg.inspectors, cls_name)
|
||||
if not inspect.isclass(real_cls):
|
||||
continue
|
||||
|
||||
patched_dict = dict(real_cls.__dict__)
|
||||
patched_dict.update({'__module__': 'drf_yasg.inspectors'})
|
||||
patched_cls = type(cls_name, real_cls.__bases__, patched_dict)
|
||||
setattr(drf_yasg.inspectors, cls_name, patched_cls)
|
||||
|
||||
for cls_name in drf_yasg.inspectors.__all__:
|
||||
# second pass - replace the inheritance bases for all classes to point to the new clean classes
|
||||
real_cls = getattr(drf_yasg.inspectors, cls_name)
|
||||
if not inspect.isclass(real_cls):
|
||||
continue
|
||||
|
||||
patched_bases = tuple(redirect_cls(base) for base in real_cls.__bases__)
|
||||
patched_cls = type(cls_name, patched_bases, dict(real_cls.__dict__))
|
||||
setattr(drf_yasg.inspectors, cls_name, patched_cls)
|
||||
|
||||
# custom interpreted role for linking to GitHub issues and pull requests
|
||||
# use as :issue:`14` or :pr:`17`
|
||||
gh_issue_uri = "https://github.com/axnsan12/drf-yasg/issues/%d"
|
||||
gh_pr_uri = "https://github.com/axnsan12/drf-yasg/pull/%d"
|
||||
gh_issue_uri = "https://github.com/axnsan12/drf-yasg/issues/{}"
|
||||
gh_pr_uri = "https://github.com/axnsan12/drf-yasg/pull/{}"
|
||||
gh_user_uri = "https://github.com/{}"
|
||||
|
||||
|
||||
def sphinx_err(inliner, lineno, rawtext, msg):
|
||||
msg = inliner.reporter.error(msg, line=lineno)
|
||||
prb = inliner.problematic(rawtext, rawtext, msg)
|
||||
return [prb], [msg]
|
||||
|
||||
|
||||
def sphinx_ref(options, rawtext, text, ref):
|
||||
set_classes(options)
|
||||
node = nodes.reference(rawtext, text, refuri=ref, **options)
|
||||
return [node], []
|
||||
|
||||
|
||||
def role_github_user(name, rawtext, text, lineno, inliner, options=None, content=None):
|
||||
options = options or {}
|
||||
content = content or []
|
||||
|
||||
if not re.match(r"^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$", text):
|
||||
return sphinx_err(inliner, lineno, rawtext, '"%s" is not a valid GitHub username.' % text)
|
||||
|
||||
ref = gh_user_uri.format(text)
|
||||
text = '@' + utils.unescape(text)
|
||||
return sphinx_ref(options, rawtext, text, ref)
|
||||
|
||||
|
||||
def role_github_pull_request_or_issue(name, rawtext, text, lineno, inliner, options=None, content=None):
|
||||
options = options or {}
|
||||
content = content or []
|
||||
try:
|
||||
ghid = int(text)
|
||||
if ghid <= 0:
|
||||
if int(text) <= 0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
msg = inliner.reporter.error(
|
||||
'GitHub pull request or issue number must be a number greater than or equal to 1; '
|
||||
'"%s" is invalid.' % text, line=lineno
|
||||
return sphinx_err(
|
||||
inliner, lineno, rawtext,
|
||||
'GitHub pull request or issue number must be a number greater than or equal to 1; "%s" is invalid.' % text
|
||||
)
|
||||
prb = inliner.problematic(rawtext, rawtext, msg)
|
||||
return [prb], [msg]
|
||||
# Base URL mainly used by inliner.rfc_reference, so this is correct:
|
||||
|
||||
if name == 'pr':
|
||||
ref = gh_pr_uri
|
||||
elif name == 'issue':
|
||||
ref = gh_issue_uri
|
||||
else:
|
||||
msg = inliner.reporter.error('unknown tag name for GitHub reference - "%s"' % name, line=lineno)
|
||||
prb = inliner.problematic(rawtext, rawtext, msg)
|
||||
return [prb], [msg]
|
||||
return sphinx_err(inliner, lineno, rawtext, 'unknown role name for GitHub reference - "%s"' % name)
|
||||
|
||||
ref = ref % ghid
|
||||
set_classes(options)
|
||||
node = nodes.reference(rawtext, '#' + utils.unescape(text), refuri=ref, **options)
|
||||
return [node], []
|
||||
ref = ref.format(text)
|
||||
text = '#' + utils.unescape(text)
|
||||
return sphinx_ref(options, rawtext, text, ref)
|
||||
|
||||
|
||||
roles.register_local_role('pr', role_github_pull_request_or_issue)
|
||||
roles.register_local_role('issue', role_github_pull_request_or_issue)
|
||||
roles.register_local_role('ghuser', role_github_user)
|
||||
|
||||
|
||||
def setup(app):
|
||||
app.add_stylesheet('css/style.css')
|
||||
|
||||
+217
-7
@@ -127,7 +127,39 @@ This section describes where information is sourced from when using the default
|
||||
* *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.
|
||||
|
||||
|
||||
.. versionadded:: 1.2
|
||||
Base path and versioning support.
|
||||
|
||||
.. _custom-spec-swagger-auto-schema:
|
||||
|
||||
@@ -138,7 +170,7 @@ The ``@swagger_auto_schema`` decorator
|
||||
You can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decorator on view functions to override
|
||||
some properties of the generated :class:`.Operation`. For example, in a ``ViewSet``,
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
@swagger_auto_schema(operation_description="partial_update description override", responses={404: 'slug not found'})
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
@@ -153,12 +185,14 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
|
||||
* for function based ``@api_view``\ s, because the same view can handle multiple methods, and thus represent multiple
|
||||
operations, you have to add the decorator multiple times if you want to override different operations:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
test_param = openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)
|
||||
user_response = openapi.Response('response description', UserSerializer)
|
||||
|
||||
# 'method' can be used to customize a single HTTP method of a view
|
||||
@swagger_auto_schema(method='get', manual_parameters=[test_param], responses={200: user_response})
|
||||
# 'methods' can be used to apply the same modification to multiple methods
|
||||
@swagger_auto_schema(methods=['put', 'post'], request_body=UserSerializer)
|
||||
@api_view(['GET', 'PUT', 'POST'])
|
||||
def user_detail(request, pk):
|
||||
@@ -167,7 +201,7 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
|
||||
* for class based ``APIView``, ``GenericAPIView`` and non-``ViewSet`` derivatives, you have to decorate the respective
|
||||
method of each operation:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
class UserList(APIView):
|
||||
@swagger_auto_schema(responses={200: UserSerializer(many=True)})
|
||||
@@ -184,9 +218,10 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
|
||||
respond to multiple HTTP methods and thus have multiple operations that must be decorated separately:
|
||||
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
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'])
|
||||
def today(self, request):
|
||||
@@ -206,16 +241,103 @@ Where you can use the :func:`@swagger_auto_schema <.swagger_auto_schema>` decora
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
...
|
||||
|
||||
.. Tip::
|
||||
|
||||
If you want to customize the generation of a method you are not implementing yourself, you can use
|
||||
``swagger_auto_schema`` in combination with Django's ``method_decorator``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@method_decorator(name='list', decorator=swagger_auto_schema(
|
||||
operation_description="description from swagger_auto_schema via method_decorator"
|
||||
))
|
||||
class ArticleViewSet(viewsets.ModelViewSet):
|
||||
...
|
||||
|
||||
This allows you to avoid unnecessarily overriding the method.
|
||||
|
||||
.. Tip::
|
||||
|
||||
You can go even further and directly decorate the result of ``as_view``, in the same manner you would
|
||||
override an ``@api_view`` as described above:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
decorated_login_view = \
|
||||
swagger_auto_schema(
|
||||
method='post',
|
||||
responses={status.HTTP_200_OK: LoginResponseSerializer}
|
||||
)(LoginView.as_view())
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
url(r'^login/$', decorated_login_view, name='login')
|
||||
]
|
||||
|
||||
This can allow you to avoid skipping an unnecessary *subclass* altogether.
|
||||
|
||||
.. Warning::
|
||||
|
||||
However, do note that both of the methods above can lead to unexpected (and maybe surprising) results by
|
||||
replacing/decorating methods on the base class itself.
|
||||
|
||||
|
||||
********************************
|
||||
Serializer ``Meta`` nested class
|
||||
********************************
|
||||
|
||||
You can define some per-serializer options by adding a ``Meta`` class to your serializer, e.g.:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class WhateverSerializer(Serializer):
|
||||
...
|
||||
|
||||
class Meta:
|
||||
... options here ...
|
||||
|
||||
Currently, the only option you can add here is
|
||||
|
||||
* ``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
|
||||
|
||||
*************************
|
||||
Subclassing and extending
|
||||
*************************
|
||||
|
||||
For more advanced control you can subclass :class:`.SwaggerAutoSchema` - see the documentation page for a list of
|
||||
methods you can override.
|
||||
|
||||
---------------------
|
||||
``SwaggerAutoSchema``
|
||||
---------------------
|
||||
|
||||
For more advanced control you can subclass :class:`~.inspectors.SwaggerAutoSchema` - see the documentation page
|
||||
for a list of methods you can override.
|
||||
|
||||
You can put your custom subclass to use by setting it on a view method using the
|
||||
:func:`@swagger_auto_schema <.swagger_auto_schema>` decorator described above.
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>` decorator described above, by setting it as a
|
||||
class-level attribute named ``swagger_schema`` on the view class, or
|
||||
:ref:`globally via settings <default-class-settings>`.
|
||||
|
||||
For example, to generate all operation IDs as camel case, you could do:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from inflection import camelize
|
||||
|
||||
class CamelCaseOperationIDAutoSchema(SwaggerAutoSchema):
|
||||
def get_operation_id(self, operation_keys):
|
||||
operation_id = super(CamelCaseOperationIDAutoSchema, self).get_operation_id(operation_keys)
|
||||
return camelize(operation_id, uppercase_first_letter=False)
|
||||
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'DEFAULT_AUTO_SCHEMA_CLASS': 'path.to.CamelCaseOperationIDAutoSchema',
|
||||
...
|
||||
}
|
||||
|
||||
--------------------------
|
||||
``OpenAPISchemaGenerator``
|
||||
--------------------------
|
||||
|
||||
If you need to control things at a higher level than :class:`.Operation` objects (e.g. overall document structure,
|
||||
vendor extensions in metadata) you can also subclass :class:`.OpenAPISchemaGenerator` - again, see the documentation
|
||||
@@ -223,3 +345,91 @@ page for a list of its methods.
|
||||
|
||||
This custom generator can be put to use by setting it as the :attr:`.generator_class` of a :class:`.SchemaView` using
|
||||
:func:`.get_schema_view`.
|
||||
|
||||
.. _custom-spec-inspectors:
|
||||
|
||||
---------------------
|
||||
``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
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>` or one of the
|
||||
:ref:`related settings <default-class-settings>`.
|
||||
|
||||
A :class:`~.inspectors.FilterInspector` that adds a description to all ``DjangoFilterBackend`` parameters could be
|
||||
implemented like so:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class DjangoFilterDescriptionInspector(CoreAPICompatInspector):
|
||||
def get_filter_parameters(self, filter_backend):
|
||||
if isinstance(filter_backend, DjangoFilterBackend):
|
||||
result = super(DjangoFilterDescriptionInspector, self).get_filter_parameters(filter_backend)
|
||||
for param in result:
|
||||
if not param.get('description', ''):
|
||||
param.description = "Filter the returned list by {field_name}".format(field_name=param.name)
|
||||
|
||||
return result
|
||||
|
||||
return NotHandled
|
||||
|
||||
@method_decorator(name='list', decorator=swagger_auto_schema(
|
||||
filter_inspectors=[DjangoFilterDescriptionInspector]
|
||||
))
|
||||
class ArticleViewSet(viewsets.ModelViewSet):
|
||||
filter_backends = (DjangoFilterBackend,)
|
||||
filter_fields = ('title',)
|
||||
...
|
||||
|
||||
|
||||
A second example, of a :class:`~.inspectors.FieldInspector` that removes the ``title`` attribute from all generated
|
||||
:class:`.Schema` objects:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class NoSchemaTitleInspector(FieldInspector):
|
||||
def process_result(self, result, method_name, obj, **kwargs):
|
||||
# remove the `title` attribute of all Schema objects
|
||||
if isinstance(result, openapi.Schema.OR_REF):
|
||||
# traverse any references and alter the Schema object in place
|
||||
schema = openapi.resolve_ref(result, self.components)
|
||||
schema.pop('title', None)
|
||||
|
||||
# no ``return schema`` here, because it would mean we always generate
|
||||
# an inline `object` instead of a definition reference
|
||||
|
||||
# return back the same object that we got - i.e. a reference if we got a reference
|
||||
return result
|
||||
|
||||
|
||||
class NoTitleAutoSchema(SwaggerAutoSchema):
|
||||
field_inspectors = [NoSchemaTitleInspector] + swagger_settings.DEFAULT_FIELD_INSPECTORS
|
||||
|
||||
class ArticleViewSet(viewsets.ModelViewSet):
|
||||
swagger_schema = NoTitleAutoSchema
|
||||
...
|
||||
|
||||
|
||||
.. Note::
|
||||
|
||||
A note on references - :class:`.Schema` objects are sometimes output by reference (:class:`.SchemaRef`); in fact,
|
||||
that is how named models are implemented in OpenAPI:
|
||||
|
||||
- in the output swagger document there is a ``definitions`` section containing :class:`.Schema` objects for all
|
||||
models
|
||||
- every usage of a model refers to that single :class:`.Schema` object - for example, in the ArticleViewSet
|
||||
above, all requests and responses containg an ``Article`` model would refer to the same schema definition by a
|
||||
``'$ref': '#/definitions/Article'``
|
||||
|
||||
This is implemented by only generating **one** :class:`.Schema` object for every serializer **class** encountered.
|
||||
|
||||
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.
|
||||
|
||||
.. _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
|
||||
|
||||
+3
-9
@@ -1,14 +1,6 @@
|
||||
drf\_yasg package
|
||||
====================
|
||||
|
||||
drf\_yasg\.app\_settings
|
||||
----------------------------------
|
||||
|
||||
.. automodule:: drf_yasg.app_settings
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
drf\_yasg\.codecs
|
||||
---------------------------
|
||||
|
||||
@@ -16,7 +8,7 @@ drf\_yasg\.codecs
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:exclude-members: SaneYamlDumper
|
||||
:exclude-members: SaneYamlDumper,SaneYamlLoader
|
||||
|
||||
drf\_yasg\.errors
|
||||
---------------------------
|
||||
@@ -37,6 +29,8 @@ drf\_yasg\.generators
|
||||
drf\_yasg\.inspectors
|
||||
-------------------------------
|
||||
|
||||
.. autodata:: drf_yasg.inspectors.NotHandled
|
||||
|
||||
.. automodule:: drf_yasg.inspectors
|
||||
:members:
|
||||
:undoc-members:
|
||||
|
||||
+53
-1
@@ -2,6 +2,7 @@
|
||||
Serving the schema
|
||||
##################
|
||||
|
||||
|
||||
************************************************
|
||||
``get_schema_view`` and the ``SchemaView`` class
|
||||
************************************************
|
||||
@@ -14,7 +15,7 @@ in the README for a usage example.
|
||||
|
||||
You can also subclass :class:`.SchemaView` by extending the return value of :func:`.get_schema_view`, e.g.:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
SchemaView = get_schema_view(info, ...)
|
||||
|
||||
@@ -33,3 +34,54 @@ codec and the view.
|
||||
|
||||
You can use your custom renderer classes as kwargs to :meth:`.SchemaView.as_cached_view` or by subclassing
|
||||
:class:`.SchemaView`.
|
||||
|
||||
.. _management-command:
|
||||
|
||||
******************
|
||||
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:
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ python manage.py generate_swagger swagger.json
|
||||
|
||||
See the command help for more advanced options:
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ python manage.py generate_swagger --help
|
||||
usage: manage.py generate_swagger [-h] [--version] [-v {0,1,2,3}]
|
||||
... more options ...
|
||||
|
||||
|
||||
.. Note::
|
||||
|
||||
The :ref:`DEFAULT_INFO <default-swagger-settings>` setting must be defined when using the ``generate_swagger``
|
||||
command. For example, the :ref:`README quickstart <readme-quickstart>` code could be modified as such:
|
||||
|
||||
In ``settings.py``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'DEFAULT_INFO': 'import.path.to.urls.api_info',
|
||||
}
|
||||
|
||||
In ``urls.py``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
api_info = openapi.Info(
|
||||
title="Snippets API",
|
||||
... other arguments ...
|
||||
)
|
||||
|
||||
schema_view = get_schema_view(
|
||||
# the info argument is no longer needed here as it will be picked up from DEFAULT_INFO
|
||||
... other arguments ...
|
||||
)
|
||||
|
||||
+84
-3
@@ -15,7 +15,7 @@ Example:
|
||||
|
||||
**settings.py**
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'SECURITY_DEFINITIONS': {
|
||||
@@ -37,6 +37,84 @@ The possible settings and their default values are as follows:
|
||||
``SWAGGER_SETTINGS``
|
||||
********************
|
||||
|
||||
|
||||
.. _default-class-settings:
|
||||
|
||||
Default classes
|
||||
===============
|
||||
|
||||
DEFAULT_AUTO_SCHEMA_CLASS
|
||||
-------------------------
|
||||
|
||||
:class:`~.inspectors.ViewInspector` subclass that will be used by default for generating :class:`.Operation`
|
||||
objects when iterating over endpoints. Can be overriden by using the `auto_schema` argument of
|
||||
:func:`@swagger_auto_schema <.swagger_auto_schema>` or by a ``swagger_schema`` attribute on the view class.
|
||||
|
||||
**Default**: :class:`drf_yasg.inspectors.SwaggerAutoSchema`
|
||||
|
||||
DEFAULT_FIELD_INSPECTORS
|
||||
------------------------
|
||||
|
||||
List of :class:`~.inspectors.FieldInspector` subclasses that will be used by default for inspecting serializers and
|
||||
serializer fields. Field inspectors given to :func:`@swagger_auto_schema <.swagger_auto_schema>` will be prepended
|
||||
to this list.
|
||||
|
||||
**Default**: ``[`` |br| \
|
||||
:class:`'drf_yasg.inspectors.CamelCaseJSONFilter' <.inspectors.CamelCaseJSONFilter>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.ReferencingSerializerInspector' <.inspectors.ReferencingSerializerInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.RelatedFieldInspector' <.inspectors.RelatedFieldInspector>`, |br| \
|
||||
: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.SimpleFieldInspector' <.inspectors.SimpleFieldInspector>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.StringDefaultFieldInspector' <.inspectors.StringDefaultFieldInspector>`, |br| \
|
||||
``]``
|
||||
|
||||
DEFAULT_FILTER_INSPECTORS
|
||||
-------------------------
|
||||
|
||||
List of :class:`~.inspectors.FilterInspector` subclasses that will be used by default for inspecting filter backends.
|
||||
Filter inspectors given to :func:`@swagger_auto_schema <.swagger_auto_schema>` will be prepended to this list.
|
||||
|
||||
**Default**: ``[`` |br| \
|
||||
:class:`'drf_yasg.inspectors.CoreAPICompatInspector' <.inspectors.CoreAPICompatInspector>`, |br| \
|
||||
``]``
|
||||
|
||||
DEFAULT_PAGINATOR_INSPECTORS
|
||||
----------------------------
|
||||
|
||||
List of :class:`~.inspectors.PaginatorInspector` subclasses that will be used by default for inspecting paginators.
|
||||
Paginator inspectors given to :func:`@swagger_auto_schema <.swagger_auto_schema>` will be prepended to this list.
|
||||
|
||||
**Default**: ``[`` |br| \
|
||||
:class:`'drf_yasg.inspectors.DjangoRestResponsePagination' <.inspectors.DjangoRestResponsePagination>`, |br| \
|
||||
:class:`'drf_yasg.inspectors.CoreAPICompatInspector' <.inspectors.CoreAPICompatInspector>`, |br| \
|
||||
``]``
|
||||
|
||||
Swagger document attributes
|
||||
===========================
|
||||
|
||||
.. _default-swagger-settings:
|
||||
|
||||
DEFAULT_INFO
|
||||
------------
|
||||
|
||||
An import string to an :class:`.openapi.Info` object. This will be used when running the ``generate_swagger``
|
||||
management command, or if no ``info`` argument is passed to ``get_schema_view``.
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
DEFAULT_API_URL
|
||||
---------------
|
||||
|
||||
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.
|
||||
|
||||
See also: :ref:`documentation on base URL construction <custom-spec-base-url>`
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
Authorization
|
||||
=============
|
||||
|
||||
@@ -70,7 +148,7 @@ See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#sec
|
||||
|
||||
**Default**:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
'basic': {
|
||||
'type': 'basic'
|
||||
@@ -161,7 +239,7 @@ DEFAULT_MODEL_DEPTH
|
||||
|
||||
Controls how many levels are expaned by default when showing nested models.
|
||||
|
||||
**Default**: :python:`2` |br|
|
||||
**Default**: :python:`3` |br|
|
||||
*Maps to parameter*: ``defaultModelExpandDepth``
|
||||
|
||||
******************
|
||||
@@ -199,3 +277,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
+368
-3
@@ -3,10 +3,375 @@
|
||||
"requires": true,
|
||||
"lockfileVersion": 1,
|
||||
"dependencies": {
|
||||
"argparse": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.9.tgz",
|
||||
"integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=",
|
||||
"requires": {
|
||||
"sprintf-js": "1.0.3"
|
||||
}
|
||||
},
|
||||
"autolinker": {
|
||||
"version": "0.15.3",
|
||||
"resolved": "https://registry.npmjs.org/autolinker/-/autolinker-0.15.3.tgz",
|
||||
"integrity": "sha1-NCQX2PLzRhsUzwkIjV7fh5HcmDI="
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"clipboard": {
|
||||
"version": "1.7.1",
|
||||
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-1.7.1.tgz",
|
||||
"integrity": "sha1-Ng1taUbpmnof7zleQrqStem1oWs=",
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"good-listener": "1.2.2",
|
||||
"select": "1.1.2",
|
||||
"tiny-emitter": "2.0.2"
|
||||
}
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"debug": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
|
||||
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
|
||||
"requires": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"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=="
|
||||
},
|
||||
"esprima": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz",
|
||||
"integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw=="
|
||||
},
|
||||
"foreach": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz",
|
||||
"integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k="
|
||||
},
|
||||
"format-util": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/format-util/-/format-util-1.0.3.tgz",
|
||||
"integrity": "sha1-Ay3KShFiYqEsQ/TD7IVmQWxbLZU="
|
||||
},
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz",
|
||||
"integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM="
|
||||
},
|
||||
"inherits": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
|
||||
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
|
||||
},
|
||||
"isarray": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
|
||||
},
|
||||
"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==",
|
||||
"requires": {
|
||||
"argparse": "1.0.9",
|
||||
"esprima": "4.0.0"
|
||||
}
|
||||
},
|
||||
"json-pointer": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/json-pointer/-/json-pointer-0.6.0.tgz",
|
||||
"integrity": "sha1-jlAFUKaqxUZKRzN32leqbMIoKNc=",
|
||||
"requires": {
|
||||
"foreach": "2.0.5"
|
||||
}
|
||||
},
|
||||
"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==",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"lunr": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lunr/-/lunr-1.0.0.tgz",
|
||||
"integrity": "sha1-XJJ2ySyRrDWpJBtQGNRnI9kuL18="
|
||||
},
|
||||
"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==",
|
||||
"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=",
|
||||
"requires": {
|
||||
"clipboard": "1.7.1"
|
||||
}
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"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==",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"redoc": {
|
||||
"version": "1.19.3",
|
||||
"resolved": "https://registry.npmjs.org/redoc/-/redoc-1.19.3.tgz",
|
||||
"integrity": "sha1-DfPx+6S92G/+nGIAEzBxUjytVec=",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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="
|
||||
},
|
||||
"select": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/select/-/select-1.1.2.tgz",
|
||||
"integrity": "sha1-DnNQrN7ICxEIUoeG7B1EGNEbOW0=",
|
||||
"optional": true
|
||||
},
|
||||
"slugify": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.2.6.tgz",
|
||||
"integrity": "sha512-796YAGnzEnLKQHAFf7H2q1nsjY/9qywSnF9ZkMUbs9he4aZaXO/zFUow0LZ95sBAiQjOX1EmGl23gTYaswiNaQ=="
|
||||
},
|
||||
"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==",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"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==",
|
||||
"requires": {
|
||||
"safe-buffer": "5.1.1"
|
||||
}
|
||||
},
|
||||
"swagger-ui-dist": {
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.6.1.tgz",
|
||||
"integrity": "sha1-uzQgV/h2COTs2DlGMDSJxjYicgY="
|
||||
"version": "3.9.0",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.9.0.tgz",
|
||||
"integrity": "sha1-eWXZZ6ds74tFWo0M2ROA/2Ss2RM="
|
||||
},
|
||||
"tiny-emitter": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/tiny-emitter/-/tiny-emitter-2.0.2.tgz",
|
||||
"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="
|
||||
},
|
||||
"ts-helpers": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/ts-helpers/-/ts-helpers-1.1.2.tgz",
|
||||
"integrity": "sha1-/Gm+nx87rtAfsaDvjUz+dIgU2DU="
|
||||
},
|
||||
"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=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "drf-yasg",
|
||||
"dependencies": {
|
||||
"swagger-ui-dist": "^3.6.1"
|
||||
"redoc": "^1.19.3",
|
||||
"swagger-ui-dist": "^3.9.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
.[validation]
|
||||
-r requirements/heroku.txt
|
||||
@@ -4,3 +4,9 @@ openapi_codec>=1.3.2
|
||||
ruamel.yaml>=0.15.34
|
||||
inflection>=0.3.1
|
||||
future>=0.16.0
|
||||
six>=1.11.0
|
||||
uritemplate>=3.0.0
|
||||
|
||||
djangorestframework>=3.7.0
|
||||
Django>=1.11.7,<2.0; python_version <= "2.7"
|
||||
Django>=1.11.7; python_version >= "3.4"
|
||||
|
||||
+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,6 +1,6 @@
|
||||
# requirements for local development
|
||||
tox>=2.9.1
|
||||
tox-battery>=0.5
|
||||
# requirements for local development to be installed via pip install -r requirements/dev.txt
|
||||
-r tox.txt
|
||||
-r test.txt
|
||||
-r lint.txt
|
||||
|
||||
# do not unpin this (see setup.py)
|
||||
setuptools_scm==1.15.6
|
||||
tox-battery>=0.5
|
||||
|
||||
@@ -1,6 +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.6.5
|
||||
sphinx_rtd_theme>=0.2.4
|
||||
Pillow>=4.3.0
|
||||
readme_renderer>=17.2
|
||||
|
||||
Django==1.11.8
|
||||
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
|
||||
@@ -0,0 +1,4 @@
|
||||
# needed to build the package setup_requires in setup.py
|
||||
|
||||
# do not unpin this (see setup.py)
|
||||
setuptools_scm==1.15.6
|
||||
@@ -1,14 +1,10 @@
|
||||
# pytest runner + plugins
|
||||
# requirements for running the tests via pytest
|
||||
pytest>=2.9
|
||||
pytest-pythonpath>=0.7.1
|
||||
pytest-cov>=2.5.1
|
||||
pytest-xdist>=1.22.0
|
||||
# latest pip version of pytest-django is more than a year old and does not support Django 2.0
|
||||
git+https://github.com/pytest-dev/pytest-django.git@94cccb956435dd7a719606744ee7608397e1eafb
|
||||
datadiff==2.0.0
|
||||
|
||||
# test project requirements
|
||||
Pillow>=4.3.0
|
||||
pygments>=2.2.0
|
||||
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"
|
||||
-r testproj.txt
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# test project requirements
|
||||
Pillow>=4.3.0
|
||||
pygments>=2.2.0
|
||||
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
|
||||
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
|
||||
detox>=0.11
|
||||
|
||||
-r setup.txt
|
||||
@@ -0,0 +1 @@
|
||||
python-3.6.4
|
||||
@@ -1,13 +1,25 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
import distutils.core
|
||||
import io
|
||||
import os
|
||||
|
||||
import random
|
||||
import string
|
||||
import sys
|
||||
from setuptools import setup, find_packages
|
||||
import distutils.core
|
||||
from setuptools import find_packages, setup
|
||||
|
||||
requirements_setup = ['setuptools_scm==1.15.6']
|
||||
|
||||
def read_req(req_file):
|
||||
with open(os.path.join('requirements', req_file)) as req:
|
||||
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 = read_req('base.txt')
|
||||
requirements_setup = read_req('setup.txt')
|
||||
requirements_validation = read_req('validation.txt')
|
||||
|
||||
|
||||
def _install_setup_requires(attrs):
|
||||
@@ -22,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;
|
||||
@@ -41,22 +53,23 @@ 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
|
||||
|
||||
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()]
|
||||
version = get_version()
|
||||
version_kwargs = {'use_scm_version': True}
|
||||
except LookupError:
|
||||
if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
|
||||
raise
|
||||
|
||||
|
||||
with io.open('README.rst', encoding='utf-8') as readme:
|
||||
description = readme.read()
|
||||
|
||||
requirements = ['djangorestframework>=3.7.0'] + read_req('base.txt')
|
||||
requirements_validation = read_req('validation.txt')
|
||||
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', include=['drf_yasg']),
|
||||
packages=find_packages('src'),
|
||||
package_dir={'': 'src'},
|
||||
include_package_data=True,
|
||||
install_requires=requirements,
|
||||
@@ -72,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',
|
||||
@@ -91,4 +105,5 @@ setup(
|
||||
'Topic :: Documentation',
|
||||
'Topic :: Software Development :: Code Generators',
|
||||
],
|
||||
**version_kwargs
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# coding=utf-8
|
||||
from pkg_resources import get_distribution, DistributionNotFound
|
||||
from pkg_resources import DistributionNotFound, get_distribution
|
||||
|
||||
__author__ = """Cristi V."""
|
||||
__email__ = 'cristi@cvjd.me'
|
||||
|
||||
@@ -2,6 +2,29 @@ from django.conf import settings
|
||||
from rest_framework.settings import perform_import
|
||||
|
||||
SWAGGER_DEFAULTS = {
|
||||
'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_INFO': None,
|
||||
'DEFAULT_API_URL': None,
|
||||
|
||||
'USE_SESSION_AUTH': True,
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'basic': {
|
||||
@@ -18,7 +41,7 @@ SWAGGER_DEFAULTS = {
|
||||
'DEEP_LINKING': False,
|
||||
'SHOW_EXTENSIONS': True,
|
||||
'DEFAULT_MODEL_RENDERING': 'model',
|
||||
'DEFAULT_MODEL_DEPTH': 2,
|
||||
'DEFAULT_MODEL_DEPTH': 3,
|
||||
}
|
||||
|
||||
REDOC_DEFAULTS = {
|
||||
@@ -28,7 +51,13 @@ REDOC_DEFAULTS = {
|
||||
'PATH_IN_MIDDLE': False,
|
||||
}
|
||||
|
||||
IMPORT_STRINGS = []
|
||||
IMPORT_STRINGS = [
|
||||
'DEFAULT_AUTO_SCHEMA_CLASS',
|
||||
'DEFAULT_FIELD_INSPECTORS',
|
||||
'DEFAULT_FILTER_INSPECTORS',
|
||||
'DEFAULT_PAGINATOR_INSPECTORS',
|
||||
'DEFAULT_INFO',
|
||||
]
|
||||
|
||||
|
||||
class AppSettings(object):
|
||||
|
||||
+39
-10
@@ -1,9 +1,10 @@
|
||||
from future.utils import raise_from
|
||||
|
||||
import copy
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
|
||||
from coreapi.compat import force_bytes
|
||||
from future.utils import raise_from
|
||||
from ruamel import yaml
|
||||
|
||||
from . import openapi
|
||||
@@ -11,22 +12,22 @@ 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)
|
||||
|
||||
|
||||
#:
|
||||
@@ -60,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):
|
||||
@@ -98,6 +106,9 @@ class OpenAPICodecJson(_OpenAPICodec):
|
||||
return json.dumps(spec)
|
||||
|
||||
|
||||
YAML_MAP_TAG = u'tag:yaml.org,2002:map'
|
||||
|
||||
|
||||
class SaneYamlDumper(yaml.SafeDumper):
|
||||
"""YamlDumper class usable for dumping ``OrderedDict`` and list instances in a standard way."""
|
||||
|
||||
@@ -122,7 +133,7 @@ class SaneYamlDumper(yaml.SafeDumper):
|
||||
|
||||
To use yaml.safe_dump(), you need the following.
|
||||
"""
|
||||
tag = u'tag:yaml.org,2002:map'
|
||||
tag = YAML_MAP_TAG
|
||||
value = []
|
||||
node = yaml.MappingNode(tag, value, flow_style=flow_style)
|
||||
if dump.alias_key is not None:
|
||||
@@ -158,7 +169,7 @@ def yaml_sane_dump(data, binary):
|
||||
* list elements are indented into their parents
|
||||
* YAML references/aliases are disabled
|
||||
|
||||
:param dict data: the data to be serializers
|
||||
:param dict data: the data to be dumped
|
||||
:param bool binary: True to return a utf-8 encoded binary object, False to return a string
|
||||
:return: the serialized YAML
|
||||
:rtype: str,bytes
|
||||
@@ -166,6 +177,24 @@ def yaml_sane_dump(data, binary):
|
||||
return yaml.dump(data, Dumper=SaneYamlDumper, default_flow_style=False, encoding='utf-8' if binary else None)
|
||||
|
||||
|
||||
class SaneYamlLoader(yaml.SafeLoader):
|
||||
def construct_odict(self, node, deep=False):
|
||||
self.flatten_mapping(node)
|
||||
return OrderedDict(self.construct_pairs(node))
|
||||
|
||||
|
||||
SaneYamlLoader.add_constructor(YAML_MAP_TAG, SaneYamlLoader.construct_odict)
|
||||
|
||||
|
||||
def yaml_sane_load(stream):
|
||||
"""Load the given YAML stream while preserving the input order for mapping items.
|
||||
|
||||
:param stream: YAML stream (can be a string or a file-like object)
|
||||
:rtype: OrderedDict
|
||||
"""
|
||||
return yaml.load(stream, Loader=SaneYamlLoader)
|
||||
|
||||
|
||||
class OpenAPICodecYaml(_OpenAPICodec):
|
||||
media_type = 'application/yaml'
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+263
-63
@@ -1,28 +1,162 @@
|
||||
from collections import defaultdict, OrderedDict
|
||||
import logging
|
||||
import re
|
||||
from collections import OrderedDict, defaultdict
|
||||
|
||||
import django.db.models
|
||||
import uritemplate
|
||||
from coreapi.compat import force_text
|
||||
from rest_framework.schemas.generators import SchemaGenerator
|
||||
from coreapi.compat import urlparse
|
||||
from django.utils.encoding import force_text
|
||||
from rest_framework import versioning
|
||||
from rest_framework.compat import URLPattern, URLResolver, get_original_route
|
||||
from rest_framework.schemas.generators import EndpointEnumerator as _EndpointEnumerator
|
||||
from rest_framework.schemas.generators import SchemaGenerator, endpoint_ordering
|
||||
from rest_framework.schemas.inspectors import get_pk_description
|
||||
|
||||
from drf_yasg.errors import SwaggerGenerationError
|
||||
|
||||
from . import openapi
|
||||
from .inspectors import SwaggerAutoSchema
|
||||
from .app_settings import swagger_settings
|
||||
from .inspectors.field import get_basic_type_info, get_queryset_field
|
||||
from .openapi import ReferenceResolver
|
||||
|
||||
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")
|
||||
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
|
||||
|
||||
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):
|
||||
"""
|
||||
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 = []
|
||||
|
||||
for pattern in patterns:
|
||||
path_regex = prefix + get_original_route(pattern)
|
||||
if isinstance(pattern, URLPattern):
|
||||
path = self.get_path_from_regex(path_regex)
|
||||
callback = pattern.callback
|
||||
url_name = pattern.name
|
||||
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
|
||||
path = self.replace_version(path, callback)
|
||||
for method in self.get_allowed_methods(callback):
|
||||
endpoint = (path, method, callback)
|
||||
api_endpoints.append(endpoint)
|
||||
|
||||
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
|
||||
)
|
||||
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`.
|
||||
|
||||
:param str s: string with backslash escapes
|
||||
:rtype: str
|
||||
"""
|
||||
# unlike .replace('\\', ''), this corectly transforms a double backslash into a single backslash
|
||||
return re.sub(r'\\(.)', r'\1', s)
|
||||
|
||||
def unescape_path(self, path):
|
||||
"""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
|
||||
|
||||
:param str path: path possibly containing
|
||||
:return: the unescaped path
|
||||
:rtype: str
|
||||
"""
|
||||
clean_path = ''
|
||||
while path:
|
||||
match = PATH_PARAMETER_RE.search(path)
|
||||
if not match:
|
||||
clean_path += self.unescape(path)
|
||||
break
|
||||
clean_path += self.unescape(path[:match.start()])
|
||||
clean_path += match.group()
|
||||
path = path[match.end():]
|
||||
|
||||
return clean_path
|
||||
|
||||
|
||||
class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
This class iterates over all registered API endpoints and returns an appropriate OpenAPI 2.0 compliant schema.
|
||||
Method implementations shamelessly stolen and adapted from rest_framework SchemaGenerator.
|
||||
Method implementations shamelessly stolen and adapted from rest-framework ``SchemaGenerator``.
|
||||
"""
|
||||
endpoint_enumerator_class = EndpointEnumerator
|
||||
|
||||
def __init__(self, info, version, url=None, 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, takes preedence over the version in `info`
|
||||
:param str url: API
|
||||
: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
|
||||
@@ -30,28 +164,41 @@ class OpenAPISchemaGenerator(object):
|
||||
self._gen = SchemaGenerator(info.title, url, info.get('description', ''), patterns, urlconf)
|
||||
self.info = info
|
||||
self.version = version
|
||||
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):
|
||||
return self._gen.url
|
||||
|
||||
def get_schema(self, request=None, public=False):
|
||||
"""Generate an :class:`.Swagger` representing the API schema.
|
||||
"""Generate a :class:`.Swagger` object representing the API schema.
|
||||
|
||||
:param rest_framework.request.Request request: the request used for filtering
|
||||
:param Request request: the request used for filtering
|
||||
accesible endpoints and finding the spec URI
|
||||
:param bool public: if True, all endpoints are included regardless of access through `request`
|
||||
|
||||
:return: the generated Swagger specification
|
||||
:rtype: openapi.Swagger
|
||||
"""
|
||||
endpoints = self.get_endpoints(None if public else request)
|
||||
endpoints = self.get_endpoints(request)
|
||||
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
|
||||
paths = self.get_paths(endpoints, components)
|
||||
paths, prefix = self.get_paths(endpoints, components, request, public)
|
||||
|
||||
url = self._gen.url
|
||||
if not url and request is not None:
|
||||
url = self.url
|
||||
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)
|
||||
_url=url, _prefix=prefix, _version=self.version, **dict(components)
|
||||
)
|
||||
|
||||
def create_view(self, callback, method, request=None):
|
||||
@@ -63,24 +210,24 @@ class OpenAPISchemaGenerator(object):
|
||||
:return: the view instance
|
||||
"""
|
||||
view = self._gen.create_view(callback, method, request)
|
||||
overrides = getattr(callback, 'swagger_auto_schema', None)
|
||||
overrides = getattr(callback, '_swagger_auto_schema', None)
|
||||
if overrides is not None:
|
||||
# decorated function based view must have its decorator information passed on to the re-instantiated view
|
||||
for method, _ in overrides.items():
|
||||
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_method.__func__, '_swagger_auto_schema', overrides)
|
||||
return view
|
||||
|
||||
def get_endpoints(self, request=None):
|
||||
"""Iterate over all the registered endpoints in the API.
|
||||
def get_endpoints(self, request):
|
||||
"""Iterate over all the registered endpoints in the API and return a fake view with the right parameters.
|
||||
|
||||
:param rest_framework.request.Request request: used for returning only endpoints available to the given request
|
||||
:param rest_framework.request.Request request: request to bind to the endpoint views
|
||||
:return: {path: (view_class, list[(http_method, view_instance)])
|
||||
:rtype: dict
|
||||
"""
|
||||
inspector = self._gen.endpoint_inspector_cls(self._gen.patterns, self._gen.urlconf)
|
||||
endpoints = inspector.get_api_endpoints()
|
||||
enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf, request=request)
|
||||
endpoints = enumerator.get_api_endpoints()
|
||||
|
||||
view_paths = defaultdict(list)
|
||||
view_cls = {}
|
||||
@@ -92,9 +239,7 @@ class OpenAPISchemaGenerator(object):
|
||||
return {path: (view_cls[path], methods) for path, methods in view_paths.items()}
|
||||
|
||||
def get_operation_keys(self, subpath, method, view):
|
||||
"""Return a list of keys that should be used to group an operation within the specification.
|
||||
|
||||
::
|
||||
"""Return a list of keys that should be used to group an operation within the specification. ::
|
||||
|
||||
/users/ ("users", "list"), ("users", "create")
|
||||
/users/{pk}/ ("users", "read"), ("users", "update"), ("users", "delete")
|
||||
@@ -110,37 +255,100 @@ class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
return self._gen.get_keys(subpath, method, view)
|
||||
|
||||
def get_paths(self, endpoints, components):
|
||||
def determine_path_prefix(self, paths):
|
||||
"""
|
||||
Given a list of all paths, return the common prefix which should be
|
||||
discounted when generating a schema structure.
|
||||
|
||||
This will be the longest common string that does not include that last
|
||||
component of the URL, or the last component before a path parameter.
|
||||
|
||||
For example: ::
|
||||
|
||||
/api/v1/users/
|
||||
/api/v1/users/{pk}/
|
||||
|
||||
The path prefix is ``/api/v1/``.
|
||||
|
||||
:param list[str] paths: list of paths
|
||||
:rtype: str
|
||||
"""
|
||||
return self._gen.determine_path_prefix(paths)
|
||||
|
||||
def get_paths(self, endpoints, components, request, public):
|
||||
"""Generate the Swagger Paths for the API from the given endpoints.
|
||||
|
||||
:param dict endpoints: endpoints as returned by get_endpoints
|
||||
:param ReferenceResolver components: resolver/container for Swagger References
|
||||
:rtype: openapi.Paths
|
||||
: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`
|
||||
: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._gen.determine_path_prefix(endpoints.keys())
|
||||
paths = OrderedDict()
|
||||
|
||||
default_schema_cls = SwaggerAutoSchema
|
||||
for path, (view_cls, methods) in sorted(endpoints.items()):
|
||||
path_parameters = self.get_path_parameters(path, view_cls)
|
||||
operations = {}
|
||||
for method, view in methods:
|
||||
if not self._gen.has_view_permissions(path, method, view):
|
||||
if not public and not self._gen.has_view_permissions(path, method, view):
|
||||
continue
|
||||
|
||||
operation_keys = self.get_operation_keys(path[len(prefix):], method, view)
|
||||
overrides = self.get_overrides(view, method)
|
||||
auto_schema_cls = overrides.get('auto_schema', default_schema_cls)
|
||||
schema = auto_schema_cls(view, path, method, overrides, components)
|
||||
operations[method.lower()] = schema.get_operation(operation_keys)
|
||||
operations[method.lower()] = self.get_operation(view, path, prefix, method, components, request)
|
||||
|
||||
if operations:
|
||||
paths[path] = openapi.PathItem(parameters=path_parameters, **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
|
||||
:meth:`~.inspectors.ViewInspector.get_operation` of a :class:`~.inspectors.ViewInspector` determined
|
||||
according to settings and :func:`@swagger_auto_schema <.swagger_auto_schema>` overrides.
|
||||
|
||||
:param view: the view associated with this endpoint
|
||||
:param str path: the path component of the operation URL
|
||||
:param str prefix: common path prefix among all endpoints
|
||||
:param str method: the http method of the operation
|
||||
:param openapi.ReferenceResolver components: referenceable components
|
||||
: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)
|
||||
|
||||
# the inspector class can be specified, in decreasing order of priorty,
|
||||
# 1. globaly via DEFAULT_AUTO_SCHEMA_CLASS
|
||||
view_inspector_cls = swagger_settings.DEFAULT_AUTO_SCHEMA_CLASS
|
||||
# 2. on the view/viewset class
|
||||
view_inspector_cls = getattr(view, 'swagger_schema', view_inspector_cls)
|
||||
# 3. on the swagger_auto_schema decorator
|
||||
view_inspector_cls = overrides.get('auto_schema', view_inspector_cls)
|
||||
|
||||
view_inspector = view_inspector_cls(view, path, method, components, request, overrides)
|
||||
return view_inspector.get_operation(operation_keys)
|
||||
|
||||
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
|
||||
API.
|
||||
|
||||
:param str path: the path
|
||||
:param type view_cls: the view that was bound to this path in urlpatterns
|
||||
:param dict[str,openapi.Operation] operations: operations defined on this path, keyed by lowercase HTTP method
|
||||
:rtype: openapi.PathItem
|
||||
"""
|
||||
path_parameters = self.get_path_parameters(path, view_cls)
|
||||
return openapi.PathItem(parameters=path_parameters, **operations)
|
||||
|
||||
def get_overrides(self, view, method):
|
||||
"""Get overrides specified for a given operation.
|
||||
@@ -153,7 +361,7 @@ class OpenAPISchemaGenerator(object):
|
||||
method = method.lower()
|
||||
action = getattr(view, 'action', method)
|
||||
action_method = getattr(view, action, None)
|
||||
overrides = getattr(action_method, 'swagger_auto_schema', {})
|
||||
overrides = getattr(action_method, '_swagger_auto_schema', {})
|
||||
if method in overrides:
|
||||
overrides = overrides[method]
|
||||
|
||||
@@ -168,36 +376,28 @@ class OpenAPISchemaGenerator(object):
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
parameters = []
|
||||
queryset = getattr(view_cls, 'queryset', None)
|
||||
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
|
||||
|
||||
for variable in uritemplate.variables(path):
|
||||
pattern = None
|
||||
type = openapi.TYPE_STRING
|
||||
description = None
|
||||
if model is not None:
|
||||
# Attempt to infer a field description if possible.
|
||||
try:
|
||||
model_field = model._meta.get_field(variable)
|
||||
except Exception: # pragma: no cover
|
||||
model_field = None
|
||||
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 model_field is not None and model_field.help_text:
|
||||
description = force_text(model_field.help_text)
|
||||
elif model_field is not None and model_field.primary_key:
|
||||
description = get_pk_description(model, model_field)
|
||||
|
||||
if hasattr(view_cls, 'lookup_value_regex') and getattr(view_cls, 'lookup_field', None) == variable:
|
||||
pattern = view_cls.lookup_value_regex
|
||||
elif isinstance(model_field, django.db.models.AutoField):
|
||||
type = openapi.TYPE_INTEGER
|
||||
if model_field and model_field.help_text:
|
||||
description = force_text(model_field.help_text)
|
||||
elif model_field and model_field.primary_key:
|
||||
description = get_pk_description(model, model_field)
|
||||
else:
|
||||
description = None
|
||||
|
||||
field = openapi.Parameter(
|
||||
name=variable,
|
||||
description=description,
|
||||
required=True,
|
||||
in_=openapi.IN_PATH,
|
||||
type=type,
|
||||
pattern=pattern,
|
||||
description=description,
|
||||
**attrs
|
||||
)
|
||||
parameters.append(field)
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from ..app_settings import swagger_settings
|
||||
from .base import (
|
||||
BaseInspector, FieldInspector, FilterInspector, NotHandled, PaginatorInspector, SerializerInspector, ViewInspector
|
||||
)
|
||||
from .field import (
|
||||
CamelCaseJSONFilter, ChoiceFieldInspector, DictFieldInspector, FileFieldInspector, InlineSerializerInspector,
|
||||
ReferencingSerializerInspector, RelatedFieldInspector, SimpleFieldInspector, StringDefaultFieldInspector
|
||||
)
|
||||
from .query import CoreAPICompatInspector, DjangoRestResponsePagination
|
||||
from .view import SwaggerAutoSchema
|
||||
|
||||
# these settings must be accesed only after definig/importing all the classes in this module to avoid ImportErrors
|
||||
ViewInspector.field_inspectors = swagger_settings.DEFAULT_FIELD_INSPECTORS
|
||||
ViewInspector.filter_inspectors = swagger_settings.DEFAULT_FILTER_INSPECTORS
|
||||
ViewInspector.paginator_inspectors = swagger_settings.DEFAULT_PAGINATOR_INSPECTORS
|
||||
|
||||
__all__ = [
|
||||
# base inspectors
|
||||
'BaseInspector', 'FilterInspector', 'PaginatorInspector', 'FieldInspector', 'SerializerInspector', 'ViewInspector',
|
||||
|
||||
# filter and pagination inspectors
|
||||
'CoreAPICompatInspector', 'DjangoRestResponsePagination',
|
||||
|
||||
# field inspectors
|
||||
'InlineSerializerInspector', 'ReferencingSerializerInspector', 'RelatedFieldInspector', 'SimpleFieldInspector',
|
||||
'FileFieldInspector', 'ChoiceFieldInspector', 'DictFieldInspector', 'StringDefaultFieldInspector',
|
||||
'CamelCaseJSONFilter',
|
||||
|
||||
# view inspectors
|
||||
'SwaggerAutoSchema',
|
||||
|
||||
# module constants
|
||||
'NotHandled',
|
||||
]
|
||||
@@ -0,0 +1,394 @@
|
||||
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
|
||||
|
||||
#: Sentinel value that inspectors must return to signal that they do not know how to handle an object
|
||||
NotHandled = object()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BaseInspector(object):
|
||||
def __init__(self, view, path, method, components, request):
|
||||
"""
|
||||
:param view: the view associated with this endpoint
|
||||
:param str path: the path component of the operation URL
|
||||
:param str method: the http method of the operation
|
||||
:param openapi.ReferenceResolver components: referenceable components
|
||||
:param Request request: the request made against the schema view; can be None
|
||||
"""
|
||||
self.view = view
|
||||
self.path = path
|
||||
self.method = method
|
||||
self.components = components
|
||||
self.request = request
|
||||
|
||||
def process_result(self, result, method_name, obj, **kwargs):
|
||||
"""After an inspector handles an object (i.e. returns a value other than :data:`.NotHandled`), all inspectors
|
||||
that were probed get the chance to alter the result, in reverse order. The inspector that handled the object
|
||||
is the first to receive a ``process_result`` call with the object it just returned.
|
||||
|
||||
This behaviour is similar to the Django request/response middleware processing.
|
||||
|
||||
If this inspector has no post-processing to do, it should just ``return result`` (the default implementation).
|
||||
|
||||
:param result: the return value of the winning inspector, or ``None`` if no inspector handled the object
|
||||
:param str method_name: name of the method that was called on the inspector
|
||||
:param obj: first argument passed to inspector method
|
||||
:param kwargs: additional arguments passed to inspector method
|
||||
:return:
|
||||
"""
|
||||
return result
|
||||
|
||||
def probe_inspectors(self, inspectors, method_name, obj, initkwargs=None, **kwargs):
|
||||
"""Probe a list of inspectors with a given object. The first inspector in the list to return a value that
|
||||
is not :data:`.NotHandled` wins.
|
||||
|
||||
:param list[type[BaseInspector]] inspectors: list of inspectors to probe
|
||||
:param str method_name: name of the target method on the inspector
|
||||
:param obj: first argument to inspector method
|
||||
:param dict initkwargs: extra kwargs for instantiating inspector class
|
||||
:param kwargs: additional arguments to inspector method
|
||||
:return: the return value of the winning inspector, or ``None`` if no inspector handled the object
|
||||
"""
|
||||
initkwargs = initkwargs or {}
|
||||
tried_inspectors = []
|
||||
|
||||
for inspector in inspectors:
|
||||
assert inspect.isclass(inspector), "inspector must be a class, not an object"
|
||||
assert issubclass(inspector, BaseInspector), "inspectors must subclass BaseInspector"
|
||||
|
||||
inspector = inspector(self.view, self.path, self.method, self.components, self.request, **initkwargs)
|
||||
tried_inspectors.append(inspector)
|
||||
method = getattr(inspector, method_name, None)
|
||||
if method is None:
|
||||
continue
|
||||
|
||||
result = method(obj, **kwargs)
|
||||
if result is not NotHandled:
|
||||
break
|
||||
else: # pragma: no cover
|
||||
logger.warning("%s ignored because no inspector in %s handled it (operation: %s)",
|
||||
obj, inspectors, method_name)
|
||||
result = None
|
||||
|
||||
for inspector in reversed(tried_inspectors):
|
||||
result = inspector.process_result(result, method_name, obj, **kwargs)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class PaginatorInspector(BaseInspector):
|
||||
"""Base inspector for paginators.
|
||||
|
||||
Responisble for determining extra query parameters and response structure added by given paginators.
|
||||
"""
|
||||
|
||||
def get_paginator_parameters(self, paginator):
|
||||
"""Get the pagination parameters for a single paginator **instance**.
|
||||
|
||||
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `paginator`.
|
||||
|
||||
:param BasePagination paginator: the paginator
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
return NotHandled
|
||||
|
||||
def get_paginated_response(self, paginator, response_schema):
|
||||
"""Add appropriate paging fields to a response :class:`.Schema`.
|
||||
|
||||
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `paginator`.
|
||||
|
||||
:param BasePagination paginator: the paginator
|
||||
:param openapi.Schema response_schema: the response schema that must be paged.
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
return NotHandled
|
||||
|
||||
|
||||
class FilterInspector(BaseInspector):
|
||||
"""Base inspector for filter backends.
|
||||
|
||||
Responsible for determining extra query parameters added by given filter backends.
|
||||
"""
|
||||
|
||||
def get_filter_parameters(self, filter_backend):
|
||||
"""Get the filter parameters for a single filter backend **instance**.
|
||||
|
||||
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `filter_backend`.
|
||||
|
||||
:param BaseFilterBackend filter_backend: the filter backend
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
return NotHandled
|
||||
|
||||
|
||||
class FieldInspector(BaseInspector):
|
||||
"""Base inspector for serializers and serializer fields. """
|
||||
|
||||
def __init__(self, view, path, method, components, request, field_inspectors):
|
||||
super(FieldInspector, self).__init__(view, path, method, components, request)
|
||||
self.field_inspectors = field_inspectors
|
||||
|
||||
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
|
||||
"""Convert a drf Serializer or Field instance into a Swagger object.
|
||||
|
||||
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `field`.
|
||||
|
||||
:param rest_framework.serializers.Field field: the source field
|
||||
:param type[openapi.SwaggerDict] swagger_object_type: should be one of Schema, Parameter, Items
|
||||
:param bool use_references: if False, forces all objects to be declared inline
|
||||
instead of by referencing other components
|
||||
:param kwargs: extra attributes for constructing the object;
|
||||
if swagger_object_type is Parameter, ``name`` and ``in_`` should be provided
|
||||
:return: the swagger object
|
||||
:rtype: openapi.Parameter,openapi.Items,openapi.Schema,openapi.SchemaRef
|
||||
"""
|
||||
return NotHandled
|
||||
|
||||
def probe_field_inspectors(self, field, swagger_object_type, use_references, **kwargs):
|
||||
"""Helper method for recursively probing `field_inspectors` to handle a given field.
|
||||
|
||||
All arguments are the same as :meth:`.field_to_swagger_object`.
|
||||
|
||||
:rtype: openapi.Parameter,openapi.Items,openapi.Schema,openapi.SchemaRef
|
||||
"""
|
||||
return self.probe_inspectors(
|
||||
self.field_inspectors, 'field_to_swagger_object', field, {'field_inspectors': self.field_inspectors},
|
||||
swagger_object_type=swagger_object_type, use_references=use_references, **kwargs
|
||||
)
|
||||
|
||||
def _get_partial_types(self, field, swagger_object_type, use_references, **kwargs):
|
||||
"""Helper method to extract generic information from a field and return a partial constructor for the
|
||||
appropriate openapi object.
|
||||
|
||||
All arguments are the same as :meth:`.field_to_swagger_object`.
|
||||
|
||||
The return value is a tuple consisting of:
|
||||
|
||||
* a function for constructing objects of `swagger_object_type`; its prototype is: ::
|
||||
|
||||
def SwaggerType(existing_object=None, **instance_kwargs):
|
||||
|
||||
This function creates an instance of `swagger_object_type`, passing the following attributes to its init,
|
||||
in order of precedence:
|
||||
|
||||
- arguments specified by the ``kwargs`` parameter of :meth:`._get_partial_types`
|
||||
- ``instance_kwargs`` passed to the constructor function
|
||||
- ``title``, ``description``, ``required`` and ``default`` inferred from the field,
|
||||
where appropriate
|
||||
|
||||
If ``existing_object`` is not ``None``, it is updated instead of creating a new object.
|
||||
|
||||
* a type that should be used for child objects if `field` is of an array type. This can currently have two
|
||||
values:
|
||||
|
||||
- :class:`.Schema` if `swagger_object_type` is :class:`.Schema`
|
||||
- :class:`.Items` if `swagger_object_type` is :class:`.Parameter` or :class:`.Items`
|
||||
|
||||
:rtype: tuple[callable,(type[openapi.Schema],type[openapi.Items])]
|
||||
"""
|
||||
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 = 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 = description if swagger_object_type != openapi.Items else None # Items has no description either
|
||||
|
||||
def SwaggerType(existing_object=None, **instance_kwargs):
|
||||
if 'required' not in instance_kwargs and swagger_object_type == openapi.Parameter:
|
||||
instance_kwargs['required'] = field.required
|
||||
|
||||
if 'default' not in instance_kwargs and swagger_object_type != openapi.Items:
|
||||
default = getattr(field, 'default', serializers.empty)
|
||||
if default is not serializers.empty:
|
||||
if callable(default):
|
||||
try:
|
||||
if hasattr(default, 'set_context'):
|
||||
default.set_context(field)
|
||||
default = default()
|
||||
except Exception: # pragma: no cover
|
||||
logger.warning("default for %s is callable but it raised an exception when "
|
||||
"called; 'default' field will not be added to schema", field, exc_info=True)
|
||||
default = None
|
||||
|
||||
if default is not None:
|
||||
try:
|
||||
default = field.to_representation(default)
|
||||
# JSON roundtrip ensures that the value is valid JSON;
|
||||
# for example, sets and tuples get transformed into lists
|
||||
default = json.loads(json.dumps(default, cls=encoders.JSONEncoder))
|
||||
except Exception: # pragma: no cover
|
||||
logger.warning("'default' on schema for %s will not be set because "
|
||||
"to_representation raised an exception", field, exc_info=True)
|
||||
default = None
|
||||
|
||||
if default is not None:
|
||||
instance_kwargs['default'] = default
|
||||
|
||||
instance_kwargs.setdefault('title', title)
|
||||
instance_kwargs.setdefault('description', description)
|
||||
instance_kwargs.update(kwargs)
|
||||
|
||||
if existing_object is not None:
|
||||
assert isinstance(existing_object, swagger_object_type)
|
||||
for attr, val in sorted(instance_kwargs.items()):
|
||||
setattr(existing_object, attr, val)
|
||||
return existing_object
|
||||
|
||||
return swagger_object_type(**instance_kwargs)
|
||||
|
||||
# arrays in Schema have Schema elements, arrays in Parameter and Items have Items elements
|
||||
child_swagger_type = openapi.Schema if swagger_object_type == openapi.Schema else openapi.Items
|
||||
return SwaggerType, child_swagger_type
|
||||
|
||||
|
||||
class SerializerInspector(FieldInspector):
|
||||
def get_schema(self, serializer):
|
||||
"""Convert a DRF Serializer instance to an :class:`.openapi.Schema`.
|
||||
|
||||
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `serializer`.
|
||||
|
||||
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
return NotHandled
|
||||
|
||||
def get_request_parameters(self, serializer, in_):
|
||||
"""Convert a DRF serializer into a list of :class:`.Parameter`\ s.
|
||||
|
||||
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `serializer`.
|
||||
|
||||
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
|
||||
:param str in_: the location of the parameters, one of the `openapi.IN_*` constants
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
return NotHandled
|
||||
|
||||
|
||||
class ViewInspector(BaseInspector):
|
||||
body_methods = ('PUT', 'PATCH', 'POST') #: methods that are allowed to have a request body
|
||||
|
||||
# real values set in __init__ to prevent import errors
|
||||
field_inspectors = [] #:
|
||||
filter_inspectors = [] #:
|
||||
paginator_inspectors = [] #:
|
||||
|
||||
def __init__(self, view, path, method, components, request, overrides):
|
||||
"""
|
||||
Inspector class responsible for providing :class:`.Operation` definitions given a view, path and method.
|
||||
|
||||
:param dict overrides: manual overrides as passed to :func:`@swagger_auto_schema <.swagger_auto_schema>`
|
||||
"""
|
||||
super(ViewInspector, self).__init__(view, path, method, components, request)
|
||||
self.overrides = overrides
|
||||
self._prepend_inspector_overrides('field_inspectors')
|
||||
self._prepend_inspector_overrides('filter_inspectors')
|
||||
self._prepend_inspector_overrides('paginator_inspectors')
|
||||
|
||||
def _prepend_inspector_overrides(self, inspectors):
|
||||
extra_inspectors = self.overrides.get(inspectors, None)
|
||||
if extra_inspectors:
|
||||
default_inspectors = [insp for insp in getattr(self, inspectors) if insp not in extra_inspectors]
|
||||
setattr(self, inspectors, extra_inspectors + default_inspectors)
|
||||
|
||||
def get_operation(self, operation_keys):
|
||||
"""Get an :class:`.Operation` for the given API endpoint (path, method).
|
||||
This includes query, body parameters and response schemas.
|
||||
|
||||
:param tuple[str] operation_keys: an array of keys describing the hierarchical layout of this view in the API;
|
||||
e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
|
||||
:rtype: openapi.Operation
|
||||
"""
|
||||
raise NotImplementedError("ViewInspector must implement get_operation()!")
|
||||
|
||||
# methods below provided as default implementations for probing inspectors
|
||||
|
||||
def should_filter(self):
|
||||
"""Determine whether filter backend parameters should be included for this request.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if not getattr(self.view, 'filter_backends', None):
|
||||
return False
|
||||
|
||||
if self.method.lower() not in ["get", "delete"]:
|
||||
return False
|
||||
|
||||
return is_list_view(self.path, self.method, self.view)
|
||||
|
||||
def get_filter_parameters(self):
|
||||
"""Return the parameters added to the view by its filter backends.
|
||||
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_filter():
|
||||
return []
|
||||
|
||||
fields = []
|
||||
for filter_backend in self.view.filter_backends:
|
||||
fields += self.probe_inspectors(self.filter_inspectors, 'get_filter_parameters', filter_backend()) or []
|
||||
|
||||
return fields
|
||||
|
||||
def should_page(self):
|
||||
"""Determine whether paging parameters and structure should be added to this operation's request and response.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if not getattr(self.view, 'paginator', None):
|
||||
return False
|
||||
|
||||
if self.method.lower() != 'get':
|
||||
return False
|
||||
|
||||
return is_list_view(self.path, self.method, self.view)
|
||||
|
||||
def get_pagination_parameters(self):
|
||||
"""Return the parameters added to the view by its paginator.
|
||||
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_page():
|
||||
return []
|
||||
|
||||
return self.probe_inspectors(self.paginator_inspectors, 'get_paginator_parameters', self.view.paginator) or []
|
||||
|
||||
def serializer_to_schema(self, serializer):
|
||||
"""Convert a serializer to an OpenAPI :class:`.Schema`.
|
||||
|
||||
: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
|
||||
"""
|
||||
return self.probe_inspectors(
|
||||
self.field_inspectors, 'get_schema', serializer, {'field_inspectors': self.field_inspectors}
|
||||
)
|
||||
|
||||
def serializer_to_parameters(self, serializer, in_):
|
||||
"""Convert a serializer to a possibly empty list of :class:`.Parameter`\ s.
|
||||
|
||||
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
|
||||
:param str in_: the location of the parameters, one of the `openapi.IN_*` constants
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
return self.probe_inspectors(
|
||||
self.field_inspectors, 'get_request_parameters', serializer, {'field_inspectors': self.field_inspectors},
|
||||
in_=in_
|
||||
) or []
|
||||
|
||||
def get_paginated_response(self, response_schema):
|
||||
"""Add appropriate paging fields to a response :class:`.Schema`.
|
||||
|
||||
:param openapi.Schema response_schema: the response schema that must be paged.
|
||||
:returns: the paginated response class:`.Schema`, or ``None`` in case of an unknown pagination scheme
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
return self.probe_inspectors(self.paginator_inspectors, 'get_paginated_response',
|
||||
self.view.paginator, response_schema=response_schema)
|
||||
@@ -0,0 +1,474 @@
|
||||
import operator
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.core import validators
|
||||
from django.db import models
|
||||
from rest_framework import serializers
|
||||
from rest_framework.settings import api_settings as rest_framework_settings
|
||||
|
||||
from .. import openapi
|
||||
from ..errors import SwaggerGenerationError
|
||||
from ..utils import filter_none
|
||||
from .base import FieldInspector, NotHandled, SerializerInspector
|
||||
|
||||
|
||||
class InlineSerializerInspector(SerializerInspector):
|
||||
"""Provides serializer conversions using :meth:`.FieldInspector.field_to_swagger_object`."""
|
||||
|
||||
#: whether to output :class:`.Schema` definitions inline or into the ``definitions`` section
|
||||
use_definitions = False
|
||||
|
||||
def get_schema(self, serializer):
|
||||
return self.probe_field_inspectors(serializer, openapi.Schema, self.use_definitions)
|
||||
|
||||
def get_request_parameters(self, serializer, in_):
|
||||
fields = getattr(serializer, 'fields', {})
|
||||
return [
|
||||
self.probe_field_inspectors(
|
||||
value, openapi.Parameter, self.use_definitions,
|
||||
name=self.get_parameter_name(key), in_=in_
|
||||
)
|
||||
for key, value
|
||||
in fields.items()
|
||||
]
|
||||
|
||||
def get_property_name(self, field_name):
|
||||
return field_name
|
||||
|
||||
def get_parameter_name(self, field_name):
|
||||
return field_name
|
||||
|
||||
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.ListSerializer, serializers.ListField)):
|
||||
child_schema = self.probe_field_inspectors(field.child, ChildSwaggerType, use_references)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=child_schema,
|
||||
)
|
||||
elif isinstance(field, serializers.Serializer):
|
||||
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')]
|
||||
|
||||
def make_schema_definition():
|
||||
properties = OrderedDict()
|
||||
required = []
|
||||
for property_name, child in serializer.fields.items():
|
||||
property_name = self.get_property_name(property_name)
|
||||
prop_kwargs = {
|
||||
'read_only': child.read_only or None
|
||||
}
|
||||
prop_kwargs = filter_none(prop_kwargs)
|
||||
|
||||
properties[property_name] = self.probe_field_inspectors(
|
||||
child, ChildSwaggerType, use_references, **prop_kwargs
|
||||
)
|
||||
if child.required:
|
||||
required.append(property_name)
|
||||
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties=properties,
|
||||
required=required or None,
|
||||
)
|
||||
|
||||
if not ref_name or not use_references:
|
||||
return make_schema_definition()
|
||||
|
||||
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
|
||||
definitions.setdefault(ref_name, make_schema_definition)
|
||||
return openapi.SchemaRef(definitions, ref_name)
|
||||
|
||||
return NotHandled
|
||||
|
||||
|
||||
class ReferencingSerializerInspector(InlineSerializerInspector):
|
||||
use_definitions = True
|
||||
|
||||
|
||||
def get_queryset_field(queryset, field_name):
|
||||
"""Try to get information about a model and model field from a queryset.
|
||||
|
||||
:param queryset: the queryset
|
||||
:param field_name: target field name
|
||||
:returns: the model and target field from the queryset as a 2-tuple; both elements can be ``None``
|
||||
:rtype: tuple
|
||||
"""
|
||||
model = getattr(queryset, 'model', None)
|
||||
model_field = get_model_field(model, field_name)
|
||||
return model, model_field
|
||||
|
||||
|
||||
def get_model_field(model, field_name):
|
||||
"""Try to get the given field from a django db model.
|
||||
|
||||
:param model: the model
|
||||
:param field_name: target field name
|
||||
:return: model field or ``None``
|
||||
"""
|
||||
try:
|
||||
if field_name == 'pk':
|
||||
return model._meta.pk
|
||||
else:
|
||||
return model._meta.get_field(field_name)
|
||||
except Exception: # pragma: no cover
|
||||
return None
|
||||
|
||||
|
||||
def get_parent_serializer(field):
|
||||
"""Get the nearest parent ``Serializer`` instance for the given field.
|
||||
|
||||
:return: ``Serializer`` or ``None``
|
||||
"""
|
||||
while field is not None:
|
||||
if isinstance(field, serializers.Serializer):
|
||||
return field
|
||||
|
||||
field = field.parent
|
||||
|
||||
return None # pragma: no cover
|
||||
|
||||
|
||||
def get_related_model(model, source):
|
||||
"""Try to find the other side of a model relationship given the name of a related field.
|
||||
|
||||
:param model: one side of the relationship
|
||||
:param str source: related field name
|
||||
:return: related model or ``None``
|
||||
"""
|
||||
try:
|
||||
return getattr(model, source).rel.related_model
|
||||
except Exception: # pragma: no cover
|
||||
return None
|
||||
|
||||
|
||||
class RelatedFieldInspector(FieldInspector):
|
||||
"""Provides conversions for ``RelatedField``\ s."""
|
||||
|
||||
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.ManyRelatedField):
|
||||
child_schema = self.probe_field_inspectors(field.child_relation, ChildSwaggerType, use_references)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=child_schema,
|
||||
unique_items=True,
|
||||
)
|
||||
|
||||
if not isinstance(field, serializers.RelatedField):
|
||||
return NotHandled
|
||||
|
||||
field_queryset = getattr(field, 'queryset', None)
|
||||
|
||||
if isinstance(field, (serializers.PrimaryKeyRelatedField, serializers.SlugRelatedField)):
|
||||
if getattr(field, 'pk_field', ''):
|
||||
# a PrimaryKeyRelatedField can have a `pk_field` attribute which is a
|
||||
# serializer field that will convert the PK value
|
||||
result = self.probe_field_inspectors(field.pk_field, swagger_object_type, use_references, **kwargs)
|
||||
# take the type, format, etc from `pk_field`, and the field-level information
|
||||
# like title, description, default from the PrimaryKeyRelatedField
|
||||
return SwaggerType(existing_object=result)
|
||||
|
||||
target_field = getattr(field, 'slug_field', 'pk')
|
||||
if field_queryset is not None:
|
||||
# if the RelatedField has a queryset, try to get the related model field from there
|
||||
model, model_field = get_queryset_field(field_queryset, target_field)
|
||||
else:
|
||||
# if the RelatedField has no queryset (e.g. read only), try to find the target model
|
||||
# from the view queryset or ModelSerializer model, if present
|
||||
view_queryset = getattr(self.view, 'queryset', None)
|
||||
serializer_meta = getattr(get_parent_serializer(field), 'Meta', None)
|
||||
this_model = getattr(view_queryset, 'model', None) or getattr(serializer_meta, 'model', None)
|
||||
source = getattr(field, 'source', '') or field.field_name
|
||||
model = get_related_model(this_model, source)
|
||||
model_field = get_model_field(model, target_field)
|
||||
|
||||
attrs = get_basic_type_info(model_field) or {'type': openapi.TYPE_STRING}
|
||||
return SwaggerType(**attrs)
|
||||
elif isinstance(field, serializers.HyperlinkedRelatedField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)
|
||||
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
|
||||
|
||||
def find_regex(regex_field):
|
||||
"""Given a ``Field``, look for a ``RegexValidator`` and try to extract its pattern and return it as a string.
|
||||
|
||||
:param serializers.Field regex_field: the field instance
|
||||
:return: the extracted pattern, or ``None``
|
||||
:rtype: str
|
||||
"""
|
||||
regex_validator = None
|
||||
for validator in regex_field.validators:
|
||||
if isinstance(validator, validators.RegexValidator):
|
||||
if regex_validator is not None:
|
||||
# bail if multiple validators are found - no obvious way to choose
|
||||
return None # pragma: no cover
|
||||
regex_validator = validator
|
||||
|
||||
# regex_validator.regex should be a compiled re object...
|
||||
pattern = getattr(getattr(regex_validator, 'regex', None), 'pattern', None)
|
||||
if pattern:
|
||||
# attempt some basic cleanup to remove regex constructs not supported by JavaScript
|
||||
# -- swagger uses javascript-style regexes - see https://github.com/swagger-api/swagger-editor/issues/1601
|
||||
if pattern.endswith('\\Z') or pattern.endswith('\\z'):
|
||||
pattern = pattern[:-2] + '$'
|
||||
|
||||
return pattern
|
||||
|
||||
|
||||
numeric_fields = (serializers.IntegerField, serializers.FloatField, serializers.DecimalField)
|
||||
limit_validators = [
|
||||
# minimum and maximum apply to numbers
|
||||
(validators.MinValueValidator, numeric_fields, 'minimum', operator.__gt__),
|
||||
(validators.MaxValueValidator, numeric_fields, 'maximum', operator.__lt__),
|
||||
|
||||
# minLength and maxLength apply to strings
|
||||
(validators.MinLengthValidator, serializers.CharField, 'min_length', operator.__gt__),
|
||||
(validators.MaxLengthValidator, serializers.CharField, 'max_length', operator.__lt__),
|
||||
|
||||
# minItems and maxItems apply to lists
|
||||
(validators.MinLengthValidator, serializers.ListField, 'min_items', operator.__gt__),
|
||||
(validators.MaxLengthValidator, serializers.ListField, 'max_items', operator.__lt__),
|
||||
]
|
||||
|
||||
|
||||
def find_limits(field):
|
||||
"""Given a ``Field``, look for min/max value/length validators and return appropriate limit validation attributes.
|
||||
|
||||
:param serializers.Field field: the field instance
|
||||
:return: the extracted limits
|
||||
:rtype: OrderedDict
|
||||
"""
|
||||
limits = {}
|
||||
applicable_limits = [
|
||||
(validator, attr, improves)
|
||||
for validator, field_class, attr, improves in limit_validators
|
||||
if isinstance(field, field_class)
|
||||
]
|
||||
|
||||
for validator in field.validators:
|
||||
if not hasattr(validator, 'limit_value'):
|
||||
continue
|
||||
|
||||
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
|
||||
|
||||
return OrderedDict(sorted(limits.items()))
|
||||
|
||||
|
||||
model_field_to_basic_type = [
|
||||
(models.AutoField, (openapi.TYPE_INTEGER, None)),
|
||||
(models.BinaryField, (openapi.TYPE_STRING, openapi.FORMAT_BINARY)),
|
||||
(models.BooleanField, (openapi.TYPE_BOOLEAN, None)),
|
||||
(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.DurationField, (openapi.TYPE_INTEGER, None)),
|
||||
(models.FloatField, (openapi.TYPE_NUMBER, None)),
|
||||
(models.IntegerField, (openapi.TYPE_INTEGER, None)),
|
||||
(models.IPAddressField, (openapi.TYPE_STRING, openapi.FORMAT_IPV4)),
|
||||
(models.GenericIPAddressField, (openapi.TYPE_STRING, openapi.FORMAT_IPV6)),
|
||||
(models.SlugField, (openapi.TYPE_STRING, openapi.FORMAT_SLUG)),
|
||||
(models.TextField, (openapi.TYPE_STRING, None)),
|
||||
(models.TimeField, (openapi.TYPE_STRING, None)),
|
||||
(models.UUIDField, (openapi.TYPE_STRING, openapi.FORMAT_UUID)),
|
||||
(models.CharField, (openapi.TYPE_STRING, None)),
|
||||
]
|
||||
|
||||
ip_format = {'ipv4': openapi.FORMAT_IPV4, 'ipv6': openapi.FORMAT_IPV6}
|
||||
|
||||
serializer_field_to_basic_type = [
|
||||
(serializers.EmailField, (openapi.TYPE_STRING, openapi.FORMAT_EMAIL)),
|
||||
(serializers.SlugField, (openapi.TYPE_STRING, openapi.FORMAT_SLUG)),
|
||||
(serializers.URLField, (openapi.TYPE_STRING, openapi.FORMAT_URI)),
|
||||
(serializers.IPAddressField, (openapi.TYPE_STRING, lambda field: ip_format.get(field.protocol, None))),
|
||||
(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.IntegerField, (openapi.TYPE_INTEGER, None)),
|
||||
((serializers.FloatField, serializers.DecimalField), (openapi.TYPE_NUMBER, None)),
|
||||
(serializers.DurationField, (openapi.TYPE_NUMBER, None)), # ?
|
||||
(serializers.DateField, (openapi.TYPE_STRING, openapi.FORMAT_DATE)),
|
||||
(serializers.DateTimeField, (openapi.TYPE_STRING, openapi.FORMAT_DATETIME)),
|
||||
(serializers.ModelField, (openapi.TYPE_STRING, None)),
|
||||
]
|
||||
|
||||
basic_type_info = serializer_field_to_basic_type + model_field_to_basic_type
|
||||
|
||||
|
||||
def get_basic_type_info(field):
|
||||
"""Given a serializer or model ``Field``, return its basic type information - ``type``, ``format``, ``pattern``,
|
||||
and any applicable min/max limit values.
|
||||
|
||||
:param field: the field instance
|
||||
:return: the extracted attributes as a dictionary, or ``None`` if the field type is not known
|
||||
:rtype: OrderedDict
|
||||
"""
|
||||
if field is None:
|
||||
return None
|
||||
|
||||
for field_class, type_format in basic_type_info:
|
||||
if isinstance(field, field_class):
|
||||
swagger_type, format = type_format
|
||||
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
|
||||
limits = find_limits(field)
|
||||
|
||||
result = OrderedDict([
|
||||
('type', swagger_type),
|
||||
('format', format),
|
||||
('pattern', pattern)
|
||||
])
|
||||
result.update(limits)
|
||||
result = filter_none(result)
|
||||
return result
|
||||
|
||||
|
||||
class SimpleFieldInspector(FieldInspector):
|
||||
"""Provides conversions for fields which can be described using just ``type``, ``format``, ``pattern``
|
||||
and min/max validators.
|
||||
"""
|
||||
|
||||
def field_to_swagger_object(self, field, swagger_object_type, use_references, **kwargs):
|
||||
type_info = get_basic_type_info(field)
|
||||
if type_info is None:
|
||||
return NotHandled
|
||||
|
||||
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
|
||||
return SwaggerType(**type_info)
|
||||
|
||||
|
||||
class ChoiceFieldInspector(FieldInspector):
|
||||
"""Provides conversions for ``ChoiceField`` and ``MultipleChoiceField``."""
|
||||
|
||||
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())
|
||||
)
|
||||
)
|
||||
elif isinstance(field, serializers.ChoiceField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, enum=list(field.choices.keys()))
|
||||
|
||||
return NotHandled
|
||||
|
||||
|
||||
class FileFieldInspector(FieldInspector):
|
||||
"""Provides conversions for ``FileField``\ s."""
|
||||
|
||||
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.FileField):
|
||||
# swagger 2.0 does not support specifics about file fields, so ImageFile gets no special treatment
|
||||
# OpenAPI 3.0 does support it, so a future implementation could handle this better
|
||||
err = SwaggerGenerationError("FileField is supported only in a formData Parameter or response Schema")
|
||||
if swagger_object_type == openapi.Schema:
|
||||
# FileField.to_representation returns URL or file name
|
||||
result = SwaggerType(type=openapi.TYPE_STRING, read_only=True)
|
||||
if getattr(field, 'use_url', rest_framework_settings.UPLOADED_FILES_USE_URL):
|
||||
result.format = openapi.FORMAT_URI
|
||||
return result
|
||||
elif swagger_object_type == openapi.Parameter:
|
||||
param = SwaggerType(type=openapi.TYPE_FILE)
|
||||
if param['in'] != openapi.IN_FORM:
|
||||
raise err # pragma: no cover
|
||||
return param
|
||||
else:
|
||||
raise err # pragma: no cover
|
||||
|
||||
return NotHandled
|
||||
|
||||
|
||||
class DictFieldInspector(FieldInspector):
|
||||
"""Provides conversion for ``DictField``."""
|
||||
|
||||
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.DictField) and swagger_object_type == openapi.Schema:
|
||||
child_schema = self.probe_field_inspectors(field.child, ChildSwaggerType, use_references)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
additional_properties=child_schema
|
||||
)
|
||||
|
||||
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
|
||||
SwaggerType, ChildSwaggerType = self._get_partial_types(field, swagger_object_type, use_references, **kwargs)
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
|
||||
|
||||
try:
|
||||
from djangorestframework_camel_case.parser import CamelCaseJSONParser
|
||||
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
|
||||
from djangorestframework_camel_case.render import camelize
|
||||
except ImportError: # pragma: no cover
|
||||
class CamelCaseJSONFilter(FieldInspector):
|
||||
"""Converts property names to camelCase if ``djangorestframework_camel_case`` is used."""
|
||||
pass
|
||||
else:
|
||||
def camelize_string(s):
|
||||
"""Hack to force ``djangorestframework_camel_case`` to camelize a plain string."""
|
||||
return next(iter(camelize({s: ''})))
|
||||
|
||||
def camelize_schema(schema_or_ref, components):
|
||||
"""Recursively camelize property names for the given schema using ``djangorestframework_camel_case``."""
|
||||
schema = openapi.resolve_ref(schema_or_ref, components)
|
||||
if getattr(schema, 'properties', {}):
|
||||
schema.properties = OrderedDict(
|
||||
(camelize_string(key), camelize_schema(val, components))
|
||||
for key, val in schema.properties.items()
|
||||
)
|
||||
|
||||
if getattr(schema, 'required', []):
|
||||
schema.required = [camelize_string(p) for p in schema.required]
|
||||
|
||||
return schema_or_ref
|
||||
|
||||
class CamelCaseJSONFilter(FieldInspector):
|
||||
"""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)
|
||||
)
|
||||
|
||||
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
|
||||
@@ -0,0 +1,76 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
import coreschema
|
||||
from rest_framework.pagination import CursorPagination, LimitOffsetPagination, PageNumberPagination
|
||||
|
||||
from .. import openapi
|
||||
from .base import FilterInspector, PaginatorInspector
|
||||
|
||||
|
||||
class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
|
||||
"""Converts ``coreapi.Field``\ s to :class:`.openapi.Parameter`\ s for filters and paginators that implement a
|
||||
``get_schema_fields`` method.
|
||||
"""
|
||||
|
||||
def get_paginator_parameters(self, paginator):
|
||||
fields = []
|
||||
if hasattr(paginator, 'get_schema_fields'):
|
||||
fields = paginator.get_schema_fields(self.view)
|
||||
|
||||
return [self.coreapi_field_to_parameter(field) for field in fields]
|
||||
|
||||
def get_filter_parameters(self, filter_backend):
|
||||
fields = []
|
||||
if hasattr(filter_backend, 'get_schema_fields'):
|
||||
fields = filter_backend.get_schema_fields(self.view)
|
||||
return [self.coreapi_field_to_parameter(field) for field in fields]
|
||||
|
||||
def coreapi_field_to_parameter(self, field):
|
||||
"""Convert an instance of `coreapi.Field` to a swagger :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:rtype: openapi.Parameter
|
||||
"""
|
||||
location_to_in = {
|
||||
'query': openapi.IN_QUERY,
|
||||
'path': openapi.IN_PATH,
|
||||
'form': openapi.IN_FORM,
|
||||
'body': openapi.IN_FORM,
|
||||
}
|
||||
coreapi_types = {
|
||||
coreschema.Integer: openapi.TYPE_INTEGER,
|
||||
coreschema.Number: openapi.TYPE_NUMBER,
|
||||
coreschema.String: openapi.TYPE_STRING,
|
||||
coreschema.Boolean: openapi.TYPE_BOOLEAN,
|
||||
}
|
||||
return openapi.Parameter(
|
||||
name=field.name,
|
||||
in_=location_to_in[field.location],
|
||||
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
|
||||
required=field.required,
|
||||
description=field.schema.description,
|
||||
)
|
||||
|
||||
|
||||
class DjangoRestResponsePagination(PaginatorInspector):
|
||||
"""Provides response schema pagination warpping for django-rest-framework's LimitOffsetPagination,
|
||||
PageNumberPagination and CursorPagination
|
||||
"""
|
||||
|
||||
def get_paginated_response(self, paginator, response_schema):
|
||||
assert response_schema.type == openapi.TYPE_ARRAY, "array return expected for paged response"
|
||||
paged_schema = None
|
||||
if isinstance(paginator, (LimitOffsetPagination, PageNumberPagination, CursorPagination)):
|
||||
has_count = not isinstance(paginator, CursorPagination)
|
||||
paged_schema = openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties=OrderedDict((
|
||||
('count', openapi.Schema(type=openapi.TYPE_INTEGER) if has_count else None),
|
||||
('next', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)),
|
||||
('previous', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)),
|
||||
('results', response_schema),
|
||||
)),
|
||||
required=['count', 'results']
|
||||
)
|
||||
|
||||
return paged_schema
|
||||
@@ -1,63 +1,22 @@
|
||||
import inspect
|
||||
from collections import OrderedDict
|
||||
|
||||
import coreschema
|
||||
from rest_framework import serializers, status
|
||||
from rest_framework.request import is_form_media_type
|
||||
from rest_framework.schemas import AutoSchema
|
||||
from rest_framework.status import is_success
|
||||
from rest_framework.viewsets import GenericViewSet
|
||||
|
||||
from . import openapi
|
||||
from .errors import SwaggerGenerationError
|
||||
from .utils import serializer_field_to_swagger, no_body, is_list_view, param_list_to_odict
|
||||
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 .base import ViewInspector
|
||||
|
||||
|
||||
def force_serializer_instance(serializer):
|
||||
"""Force `serializer` into a ``Serializer`` instance. If it is not a ``Serializer`` class or instance, raises
|
||||
an assertion error.
|
||||
|
||||
:param serializer: serializer class or instance
|
||||
:return: serializer instance
|
||||
"""
|
||||
if inspect.isclass(serializer):
|
||||
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
|
||||
return serializer()
|
||||
|
||||
assert isinstance(serializer, serializers.BaseSerializer), \
|
||||
"Serializer class or instance required, not %s" % type(serializer).__name__
|
||||
return serializer
|
||||
|
||||
|
||||
class SwaggerAutoSchema(object):
|
||||
body_methods = ('PUT', 'PATCH', 'POST') #: methods allowed to have a request body
|
||||
|
||||
def __init__(self, view, path, method, overrides, components):
|
||||
"""Inspector class responsible for providing :class:`.Operation` definitions given a
|
||||
|
||||
:param view: the view associated with this endpoint
|
||||
:param str path: the path component of the operation URL
|
||||
:param str method: the http method of the operation
|
||||
:param dict overrides: manual overrides as passed to :func:`@swagger_auto_schema <.swagger_auto_schema>`
|
||||
:param openapi.ReferenceResolver components: referenceable components
|
||||
"""
|
||||
super(SwaggerAutoSchema, self).__init__()
|
||||
class SwaggerAutoSchema(ViewInspector):
|
||||
def __init__(self, view, path, method, components, request, overrides):
|
||||
super(SwaggerAutoSchema, self).__init__(view, path, method, components, request, overrides)
|
||||
self._sch = AutoSchema()
|
||||
self.view = view
|
||||
self.path = path
|
||||
self.method = method
|
||||
self.overrides = overrides
|
||||
self.components = components
|
||||
self._sch.view = view
|
||||
|
||||
def get_operation(self, operation_keys):
|
||||
"""Get an :class:`.Operation` for the given API endpoint (path, method).
|
||||
This includes query, body parameters and response schemas.
|
||||
|
||||
:param tuple[str] operation_keys: an array of keys describing the hierarchical layout of this view in the API;
|
||||
e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
|
||||
:rtype: openapi.Operation
|
||||
"""
|
||||
consumes = self.get_consumes()
|
||||
|
||||
body = self.get_request_body_parameters(consumes)
|
||||
@@ -66,17 +25,19 @@ class SwaggerAutoSchema(object):
|
||||
parameters = [param for param in parameters if param is not None]
|
||||
parameters = self.add_manual_parameters(parameters)
|
||||
|
||||
operation_id = self.get_operation_id(operation_keys)
|
||||
description = self.get_description()
|
||||
tags = self.get_tags(operation_keys)
|
||||
|
||||
responses = self.get_responses()
|
||||
|
||||
return openapi.Operation(
|
||||
operation_id='_'.join(operation_keys),
|
||||
operation_id=operation_id,
|
||||
description=description,
|
||||
responses=responses,
|
||||
parameters=parameters,
|
||||
consumes=consumes,
|
||||
tags=[operation_keys[0]],
|
||||
tags=tags,
|
||||
)
|
||||
|
||||
def get_request_body_parameters(self, consumes):
|
||||
@@ -105,7 +66,7 @@ class SwaggerAutoSchema(object):
|
||||
else:
|
||||
if schema is None:
|
||||
schema = self.get_request_body_schema(serializer)
|
||||
return [self.make_body_parameter(schema)]
|
||||
return [self.make_body_parameter(schema)] if schema is not None else []
|
||||
|
||||
def get_view_serializer(self):
|
||||
"""Return the serializer as defined by the view's ``get_serializer()`` method.
|
||||
@@ -192,26 +153,6 @@ class SwaggerAutoSchema(object):
|
||||
responses=self.get_response_schemas(response_serializers)
|
||||
)
|
||||
|
||||
def get_paged_response_schema(self, response_schema):
|
||||
"""Add appropriate paging fields to a response :class:`.Schema`.
|
||||
|
||||
:param openapi.Schema response_schema: the response schema that must be paged.
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
assert response_schema.type == openapi.TYPE_ARRAY, "array return expected for paged response"
|
||||
paged_schema = openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties={
|
||||
'count': openapi.Schema(type=openapi.TYPE_INTEGER),
|
||||
'next': openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI),
|
||||
'previous': openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI),
|
||||
'results': response_schema,
|
||||
},
|
||||
required=['count', 'results']
|
||||
)
|
||||
|
||||
return paged_schema
|
||||
|
||||
def get_default_responses(self):
|
||||
"""Get the default responses determined for this view from the request serializer and request method.
|
||||
|
||||
@@ -219,28 +160,24 @@ class SwaggerAutoSchema(object):
|
||||
"""
|
||||
method = self.method.lower()
|
||||
|
||||
default_status = status.HTTP_200_OK
|
||||
default_status = guess_response_status(method)
|
||||
default_schema = ''
|
||||
if method == 'post':
|
||||
default_status = status.HTTP_201_CREATED
|
||||
default_schema = self.get_request_serializer() or self.get_view_serializer()
|
||||
elif method == 'delete':
|
||||
default_status = status.HTTP_204_NO_CONTENT
|
||||
elif method in ('get', 'put', 'patch'):
|
||||
if method in ('get', 'post', 'put', 'patch'):
|
||||
default_schema = self.get_request_serializer() or self.get_view_serializer()
|
||||
|
||||
default_schema = default_schema or ''
|
||||
if any(is_form_media_type(encoding) for encoding in self.get_consumes()):
|
||||
default_schema = ''
|
||||
if default_schema and not isinstance(default_schema, openapi.Schema):
|
||||
default_schema = self.serializer_to_schema(default_schema) or ''
|
||||
|
||||
if default_schema:
|
||||
if not isinstance(default_schema, openapi.Schema):
|
||||
default_schema = self.serializer_to_schema(default_schema)
|
||||
if is_list_view(self.path, self.method, self.view) and self.method.lower() == 'get':
|
||||
default_schema = openapi.Schema(type=openapi.TYPE_ARRAY, items=default_schema)
|
||||
if self.should_page():
|
||||
default_schema = self.get_paged_response_schema(default_schema)
|
||||
default_schema = self.get_paginated_response(default_schema) or default_schema
|
||||
|
||||
return {str(default_status): default_schema}
|
||||
return OrderedDict({str(default_status): default_schema})
|
||||
|
||||
def get_response_serializers(self):
|
||||
"""Return the response codes that this view is expected to return, and the serializer for each response body.
|
||||
@@ -254,7 +191,7 @@ class SwaggerAutoSchema(object):
|
||||
manual_responses = self.overrides.get('responses', None) or {}
|
||||
manual_responses = OrderedDict((str(sc), resp) for sc, resp in manual_responses.items())
|
||||
|
||||
responses = {}
|
||||
responses = OrderedDict()
|
||||
if not any(is_success(int(sc)) for sc in manual_responses if sc != 'default'):
|
||||
responses = self.get_default_responses()
|
||||
|
||||
@@ -268,7 +205,7 @@ class SwaggerAutoSchema(object):
|
||||
:return: a dictionary of status code to :class:`.Response` object
|
||||
:rtype: dict[str, openapi.Response]
|
||||
"""
|
||||
responses = {}
|
||||
responses = OrderedDict()
|
||||
for sc, serializer in response_serializers.items():
|
||||
if isinstance(serializer, str):
|
||||
response = openapi.Response(
|
||||
@@ -325,84 +262,18 @@ class SwaggerAutoSchema(object):
|
||||
|
||||
return natural_parameters + serializer_parameters
|
||||
|
||||
def should_filter(self):
|
||||
"""Determine whether filter backend parameters should be included for this request.
|
||||
def get_operation_id(self, operation_keys):
|
||||
"""Return an unique ID for this operation. The ID must be unique across
|
||||
all :class:`.Operation` objects in the API.
|
||||
|
||||
:rtype: bool
|
||||
:param tuple[str] operation_keys: an array of keys derived from the pathdescribing the hierarchical layout
|
||||
of this view in the API; e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
|
||||
:rtype: str
|
||||
"""
|
||||
if not getattr(self.view, 'filter_backends', None):
|
||||
return False
|
||||
|
||||
if self.method.lower() not in ["get", "delete"]:
|
||||
return False
|
||||
|
||||
if not isinstance(self.view, GenericViewSet):
|
||||
return True
|
||||
|
||||
return is_list_view(self.path, self.method, self.view)
|
||||
|
||||
def get_filter_backend_parameters(self, filter_backend):
|
||||
"""Get the filter parameters for a single filter backend **instance**.
|
||||
|
||||
:param BaseFilterBackend filter_backend: the filter backend
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = []
|
||||
if hasattr(filter_backend, 'get_schema_fields'):
|
||||
fields = filter_backend.get_schema_fields(self.view)
|
||||
return [self.coreapi_field_to_parameter(field) for field in fields]
|
||||
|
||||
def get_filter_parameters(self):
|
||||
"""Return the parameters added to the view by its filter backends.
|
||||
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_filter():
|
||||
return []
|
||||
|
||||
fields = []
|
||||
for filter_backend in self.view.filter_backends:
|
||||
fields += self.get_filter_backend_parameters(filter_backend())
|
||||
|
||||
return fields
|
||||
|
||||
def should_page(self):
|
||||
"""Determine whether paging parameters and structure should be added to this operation's request and response.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if not hasattr(self.view, 'paginator'):
|
||||
return False
|
||||
|
||||
if self.view.paginator is None:
|
||||
return False
|
||||
|
||||
if self.method.lower() != 'get':
|
||||
return False
|
||||
|
||||
return is_list_view(self.path, self.method, self.view)
|
||||
|
||||
def get_paginator_parameters(self, paginator):
|
||||
"""Get the pagination parameters for a single paginator **instance**.
|
||||
|
||||
:param BasePagination paginator: the paginator
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = []
|
||||
if hasattr(paginator, 'get_schema_fields'):
|
||||
fields = paginator.get_schema_fields(self.view)
|
||||
|
||||
return [self.coreapi_field_to_parameter(field) for field in fields]
|
||||
|
||||
def get_pagination_parameters(self):
|
||||
"""Return the parameters added to the view by its paginator.
|
||||
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_page():
|
||||
return []
|
||||
|
||||
return self.get_paginator_parameters(self.view.paginator)
|
||||
operation_id = self.overrides.get('operation_id', '')
|
||||
if not operation_id:
|
||||
operation_id = '_'.join(operation_keys)
|
||||
return operation_id
|
||||
|
||||
def get_description(self):
|
||||
"""Return an operation description determined as appropriate from the view's method and class docstrings.
|
||||
@@ -415,6 +286,16 @@ class SwaggerAutoSchema(object):
|
||||
description = self._sch.get_description(self.path, self.method)
|
||||
return description
|
||||
|
||||
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.
|
||||
|
||||
:param tuple[str] operation_keys: an array of keys derived from the pathdescribing the hierarchical layout
|
||||
of this view in the API; e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
|
||||
:rtype: list[str]
|
||||
"""
|
||||
return [operation_keys[0]]
|
||||
|
||||
def get_consumes(self):
|
||||
"""Return the MIME types this endpoint can consume.
|
||||
|
||||
@@ -424,62 +305,3 @@ class SwaggerAutoSchema(object):
|
||||
if all(is_form_media_type(encoding) for encoding in media_types):
|
||||
return media_types
|
||||
return media_types[:1]
|
||||
|
||||
def serializer_to_schema(self, serializer):
|
||||
"""Convert a DRF Serializer instance to an :class:`.openapi.Schema`.
|
||||
|
||||
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
|
||||
return serializer_field_to_swagger(serializer, openapi.Schema, definitions)
|
||||
|
||||
def serializer_to_parameters(self, serializer, in_):
|
||||
"""Convert a DRF serializer into a list of :class:`.Parameter`\ s using :meth:`.field_to_parameter`
|
||||
|
||||
:param serializers.BaseSerializer serializer: the ``Serializer`` instance
|
||||
:param str in_: the location of the parameters, one of the `openapi.IN_*` constants
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = getattr(serializer, 'fields', {})
|
||||
return [
|
||||
self.field_to_parameter(value, key, in_)
|
||||
for key, value
|
||||
in fields.items()
|
||||
]
|
||||
|
||||
def field_to_parameter(self, field, name, in_):
|
||||
"""Convert a DRF serializer Field to a swagger :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:param str name: the name of the parameter
|
||||
:param str in_: the location of the parameter, one of the `openapi.IN_*` constants
|
||||
:rtype: openapi.Parameter
|
||||
"""
|
||||
return serializer_field_to_swagger(field, openapi.Parameter, name=name, in_=in_)
|
||||
|
||||
def coreapi_field_to_parameter(self, field):
|
||||
"""Convert an instance of `coreapi.Field` to a swagger :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:rtype: openapi.Parameter
|
||||
"""
|
||||
location_to_in = {
|
||||
'query': openapi.IN_QUERY,
|
||||
'path': openapi.IN_PATH,
|
||||
'form': openapi.IN_FORM,
|
||||
'body': openapi.IN_FORM,
|
||||
}
|
||||
coreapi_types = {
|
||||
coreschema.Integer: openapi.TYPE_INTEGER,
|
||||
coreschema.Number: openapi.TYPE_NUMBER,
|
||||
coreschema.String: openapi.TYPE_STRING,
|
||||
coreschema.Boolean: openapi.TYPE_BOOLEAN,
|
||||
}
|
||||
return openapi.Parameter(
|
||||
name=field.name,
|
||||
in_=location_to_in[field.location],
|
||||
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
|
||||
required=field.required,
|
||||
description=field.schema.description,
|
||||
)
|
||||
@@ -0,0 +1,134 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.management.base import BaseCommand
|
||||
from rest_framework.test import APIRequestFactory, force_authenticate
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from ... import openapi
|
||||
from ...app_settings import swagger_settings
|
||||
from ...codecs import OpenAPICodecJson, OpenAPICodecYaml
|
||||
from ...generators import OpenAPISchemaGenerator
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Write the Swagger schema to disk in JSON or YAML format.'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
'output_file', metavar='output-file',
|
||||
nargs='?',
|
||||
default='-',
|
||||
type=str,
|
||||
help='Output path for generated swagger document, or "-" for stdout.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-o', '--overwrite',
|
||||
default=False, action='store_true',
|
||||
help='Overwrite the output file if it already exists. '
|
||||
'Default behavior is to stop if the output file exists.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-f', '--format', dest='format',
|
||||
default='', choices=('json', 'yaml'),
|
||||
type=str,
|
||||
help='Output format. If not given, it is guessed from the output file extension and defaults to json.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-u', '--url', dest='api_url',
|
||||
default='',
|
||||
type=str,
|
||||
help='Base API URL - sets the host and scheme attributes of the generated document.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-m', '--mock-request', dest='mock',
|
||||
default=False, action='store_true',
|
||||
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(
|
||||
'--user', dest='user',
|
||||
default='',
|
||||
help='Username of an existing user to use for mocked authentication. This option implies --mock-request.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-p', '--private',
|
||||
default=False, action="store_true",
|
||||
help='Hides endpoints not accesible to the target user. If --user is not given, only shows endpoints that '
|
||||
'are accesible to unauthenticated users.\n'
|
||||
'This has the same effect as passing public=False to get_schema_view() or '
|
||||
'OpenAPISchemaGenerator.get_schema().\n'
|
||||
'This option implies --mock-request.'
|
||||
)
|
||||
|
||||
def write_schema(self, schema, stream, format):
|
||||
if format == 'json':
|
||||
codec = OpenAPICodecJson(validators=[])
|
||||
swagger_json = codec.encode(schema)
|
||||
swagger_json = json.loads(swagger_json.decode('utf-8'), object_pairs_hook=OrderedDict)
|
||||
pretty_json = json.dumps(swagger_json, indent=4, ensure_ascii=True)
|
||||
stream.write(pretty_json)
|
||||
elif format == 'yaml':
|
||||
codec = OpenAPICodecYaml(validators=[])
|
||||
swagger_yaml = codec.encode(schema).decode('utf-8')
|
||||
# YAML is already pretty!
|
||||
stream.write(swagger_yaml)
|
||||
else: # pragma: no cover
|
||||
raise ValueError("unknown format %s" % format)
|
||||
|
||||
def get_mock_request(self, url, format, user=None):
|
||||
factory = APIRequestFactory()
|
||||
|
||||
request = factory.get(url + '/swagger.' + format)
|
||||
if user is not None:
|
||||
force_authenticate(request, user=user)
|
||||
request = APIView().initialize_request(request)
|
||||
return request
|
||||
|
||||
def handle(self, output_file, overwrite, format, api_url, mock, user, private, *args, **options):
|
||||
# disable logs of WARNING and below
|
||||
logging.disable(logging.WARNING)
|
||||
|
||||
info = getattr(swagger_settings, 'DEFAULT_INFO', None)
|
||||
if not isinstance(info, openapi.Info):
|
||||
raise ImproperlyConfigured(
|
||||
'settings.SWAGGER_SETTINGS["DEFAULT_INFO"] should be an '
|
||||
'import string pointing to an openapi.Info object'
|
||||
)
|
||||
|
||||
if not format:
|
||||
if os.path.splitext(output_file)[1] in ('.yml', '.yaml'):
|
||||
format = 'yaml'
|
||||
format = format or 'json'
|
||||
|
||||
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 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
|
||||
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=info,
|
||||
url=api_url
|
||||
)
|
||||
schema = generator.get_schema(request=request, public=not private)
|
||||
|
||||
if output_file == '-':
|
||||
self.write_schema(schema, self.stdout, format)
|
||||
else:
|
||||
# normally this would be easily done with open(mode='x'/'w'),
|
||||
# but python 2 is a pain in the ass as usual
|
||||
flags = os.O_CREAT | os.O_WRONLY
|
||||
flags = flags | (os.O_TRUNC if overwrite else os.O_EXCL)
|
||||
with os.fdopen(os.open(output_file, flags), "w") as stream:
|
||||
self.write_schema(schema, stream, format)
|
||||
@@ -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)
|
||||
|
||||
+120
-32
@@ -1,9 +1,12 @@
|
||||
import re
|
||||
from collections import OrderedDict
|
||||
|
||||
from coreapi.compat import urlparse
|
||||
from future.utils import raise_from
|
||||
from django.urls import get_script_prefix
|
||||
from inflection import camelize
|
||||
|
||||
from .utils import filter_none
|
||||
|
||||
TYPE_OBJECT = "object" #:
|
||||
TYPE_STRING = "string" #:
|
||||
TYPE_NUMBER = "number" #:
|
||||
@@ -94,8 +97,9 @@ class SwaggerDict(OrderedDict):
|
||||
raise AttributeError
|
||||
try:
|
||||
return self[make_swagger_name(item)]
|
||||
except KeyError as e:
|
||||
raise_from(AttributeError("object of class " + type(self).__name__ + " has no attribute " + item), e)
|
||||
except KeyError:
|
||||
# raise_from is EXTREMELY slow, replaced with plain raise
|
||||
raise AttributeError("object of class " + type(self).__name__ + " has no attribute " + item)
|
||||
|
||||
def __delattr__(self, item):
|
||||
if item.startswith('_'):
|
||||
@@ -207,11 +211,13 @@ 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, 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 .Paths paths: paths object
|
||||
:param dict[str,.Schema] definitions: named models
|
||||
@@ -223,16 +229,39 @@ 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.paths = paths
|
||||
self.definitions = definitions
|
||||
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):
|
||||
@@ -270,13 +299,13 @@ class PathItem(SwaggerDict):
|
||||
self.patch = patch
|
||||
self.delete = delete
|
||||
self.options = options
|
||||
self.parameters = parameters
|
||||
self.parameters = filter_none(parameters)
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
class Operation(SwaggerDict):
|
||||
def __init__(self, operation_id, responses, parameters=None, consumes=None,
|
||||
produces=None, description=None, tags=None, **extra):
|
||||
produces=None, summary=None, description=None, tags=None, **extra):
|
||||
"""Information about an API operation (path + http method combination)
|
||||
|
||||
:param str operation_id: operation ID, should be unique across all operations
|
||||
@@ -284,17 +313,19 @@ class Operation(SwaggerDict):
|
||||
:param list[.Parameter] parameters: parameters accepted
|
||||
:param list[str] consumes: content types accepted
|
||||
:param list[str] produces: content types produced
|
||||
:param str description: operation description
|
||||
: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
|
||||
"""
|
||||
super(Operation, self).__init__(**extra)
|
||||
self.operation_id = operation_id
|
||||
self.summary = summary
|
||||
self.description = description
|
||||
self.parameters = [param for param in parameters if param is not None]
|
||||
self.parameters = filter_none(parameters)
|
||||
self.responses = responses
|
||||
self.consumes = consumes
|
||||
self.produces = produces
|
||||
self.tags = tags
|
||||
self.consumes = filter_none(consumes)
|
||||
self.produces = filter_none(produces)
|
||||
self.tags = filter_none(tags)
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
@@ -309,17 +340,22 @@ class Items(SwaggerDict):
|
||||
:param .Items items: only valid if `type` is ``array``
|
||||
"""
|
||||
super(Items, self).__init__(**extra)
|
||||
assert type is not None, "type is required!"
|
||||
self.type = type
|
||||
self.format = format
|
||||
self.enum = enum
|
||||
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.
|
||||
|
||||
@@ -333,6 +369,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):
|
||||
@@ -348,43 +385,74 @@ class Parameter(SwaggerDict):
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
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):
|
||||
OR_REF = ()
|
||||
OR_REF = () #: useful for type-checking, e.g ``isinstance(obj, openapi.Schema.OR_REF)``
|
||||
|
||||
def __init__(self, description=None, required=None, type=None, properties=None, additional_properties=None,
|
||||
format=None, enum=None, pattern=None, items=None, **extra):
|
||||
def __init__(self, title=None, description=None, type=None, format=None, enum=None, pattern=None, properties=None,
|
||||
additional_properties=None, required=None, items=None, default=None, read_only=None, **extra):
|
||||
"""Describes a complex object accepted as parameter or returned as a response.
|
||||
|
||||
:param description: schema description
|
||||
:param list[str] required: list of requried property names
|
||||
:param str title: schema title
|
||||
:param str description: schema description
|
||||
:param str type: value type; required
|
||||
:param list[.Schema,.SchemaRef] properties: object properties; required if `type` is ``object``
|
||||
:param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties`
|
||||
:param str format: value format, see OpenAPI spec
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param .Schema,.SchemaRef items: only valid if `type` is ``array``
|
||||
:param list[.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``
|
||||
:param default: only valid when insider another ``Schema``\ 's ``properties``;
|
||||
the default value of this property if it is not provided, must conform to the type of this Schema
|
||||
:param read_only: only valid when insider another ``Schema``\ 's ``properties``;
|
||||
declares the property as read only - it must only be sent as part of responses, never in requests
|
||||
"""
|
||||
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!")
|
||||
raise AssertionError("the `requires` 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 = required
|
||||
self.required = filter_none(required)
|
||||
self.type = type
|
||||
self.properties = properties
|
||||
self.properties = filter_none(properties)
|
||||
self.additional_properties = additional_properties
|
||||
self.format = format
|
||||
self.enum = enum
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
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):
|
||||
"""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.
|
||||
@@ -402,6 +470,15 @@ class _Ref(SwaggerDict):
|
||||
.format(actual=type(obj).__name__, expected=expected_type.__name__)
|
||||
self.ref = ref_name
|
||||
|
||||
def resolve(self, resolver):
|
||||
"""Get the object targeted by this reference from the given component resolver.
|
||||
|
||||
:param .ReferenceResolver resolver: component resolver which must contain the referneced object
|
||||
:returns: the target object
|
||||
"""
|
||||
ref_match = self.ref_name_re.match(self.ref)
|
||||
return resolver.get(ref_match.group('name'), scope=ref_match.group('scope'))
|
||||
|
||||
def __setitem__(self, key, value, **kwargs):
|
||||
if key == "$ref":
|
||||
return super(_Ref, self).__setitem__(key, value, **kwargs)
|
||||
@@ -425,6 +502,17 @@ class SchemaRef(_Ref):
|
||||
Schema.OR_REF = (Schema, SchemaRef)
|
||||
|
||||
|
||||
def resolve_ref(ref_or_obj, resolver):
|
||||
"""Resolve `ref_or_obj` if it is a reference type. Return it unchaged if not.
|
||||
|
||||
:param SwaggerDict,_Ref ref_or_obj:
|
||||
:param resolver: component resolver which must contain the referenced object
|
||||
"""
|
||||
if isinstance(ref_or_obj, _Ref):
|
||||
return ref_or_obj.resolve(resolver)
|
||||
return ref_or_obj
|
||||
|
||||
|
||||
class Responses(SwaggerDict):
|
||||
def __init__(self, responses, default=None, **extra):
|
||||
"""Describes the expected responses of an :class:`.Operation`.
|
||||
@@ -481,7 +569,7 @@ class ReferenceResolver(object):
|
||||
self._objects[scope] = OrderedDict()
|
||||
|
||||
def with_scope(self, scope):
|
||||
"""Return a new :class:`.ReferenceResolver` whose scope is defaulted and forced to `scope`.
|
||||
"""Return a view into this :class:`.ReferenceResolver` whose scope is defaulted and forced to `scope`.
|
||||
|
||||
:param str scope: target scope, must be in this resolver's `scopes`
|
||||
:return: the bound resolver
|
||||
|
||||
@@ -2,19 +2,19 @@ from django.shortcuts import render, resolve_url
|
||||
from rest_framework.renderers import BaseRenderer
|
||||
from rest_framework.utils import json
|
||||
|
||||
from .app_settings import swagger_settings, redoc_settings
|
||||
from .codecs import OpenAPICodecJson, VALIDATORS, OpenAPICodecYaml
|
||||
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']
|
||||
validators = []
|
||||
codec_class = None
|
||||
|
||||
@classmethod
|
||||
def with_validators(cls, validators):
|
||||
assert all(vld in VALIDATORS for vld in validators), "allowed validators are" + ", ".join(VALIDATORS)
|
||||
assert all(vld in VALIDATORS for vld in validators), "allowed validators are " + ", ".join(VALIDATORS)
|
||||
return type(cls.__name__, (cls,), {'validators': validators})
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
@@ -45,7 +45,7 @@ class SwaggerYAMLRenderer(_SpecRenderer):
|
||||
|
||||
|
||||
class _UIRenderer(BaseRenderer):
|
||||
"""Base class for web UI renderers. Handles loading an passing settings to the appropriate template."""
|
||||
"""Base class for web UI renderers. Handles loading and passing settings to the appropriate template."""
|
||||
media_type = 'text/html'
|
||||
charset = 'utf-8'
|
||||
template = ''
|
||||
@@ -84,6 +84,7 @@ class _UIRenderer(BaseRenderer):
|
||||
'showExtensions': swagger_settings.SHOW_EXTENSIONS,
|
||||
'defaultModelRendering': swagger_settings.DEFAULT_MODEL_RENDERING,
|
||||
'defaultModelExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
|
||||
'defaultModelsExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
|
||||
}
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if swagger_settings.VALIDATOR_URL != '':
|
||||
@@ -116,3 +117,11 @@ class ReDocRenderer(_UIRenderer):
|
||||
"""
|
||||
template = 'drf-yasg/redoc.html'
|
||||
format = 'redoc'
|
||||
|
||||
|
||||
class ReDocAlphaRenderer(_UIRenderer):
|
||||
"""Renders a ReDoc web interface for schema browisng.
|
||||
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
|
||||
"""
|
||||
template = 'drf-yasg/redoc-alpha.html'
|
||||
format = 'redoc'
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
# Swagger UI Dist
|
||||
[](http://badge.fury.io/js/swagger-ui-dist)
|
||||
|
||||
# API
|
||||
|
||||
This module, `swagger-ui-dist`, exposes Swagger-UI's entire dist folder as a dependency-free npm module.
|
||||
Use `swagger-ui` instead, if you'd like to have npm install dependencies for you.
|
||||
|
||||
`SwaggerUIBundle` and `SwaggerUIStandalonePreset` can be imported:
|
||||
```javascript
|
||||
import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist"
|
||||
```
|
||||
|
||||
To get an absolute path to this directory for static file serving, use the exported `getAbsoluteFSPath` method:
|
||||
|
||||
```javascript
|
||||
const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath()
|
||||
|
||||
// then instantiate server that serves files from the swaggerUiAssetPath
|
||||
```
|
||||
|
||||
For anything else, check the [Swagger-UI](https://github.com/swagger-api/swagger-ui) repository.
|
||||
@@ -1,95 +0,0 @@
|
||||
<!-- HTML for static distribution bundle build -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Swagger UI</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" type="text/css" href="./swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body {
|
||||
margin:0;
|
||||
background: #fafafa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 20 20" id="unlocked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="locked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="close">
|
||||
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow">
|
||||
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow-down">
|
||||
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
|
||||
</symbol>
|
||||
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="jump-to">
|
||||
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="expand">
|
||||
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
|
||||
</symbol>
|
||||
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="./swagger-ui-bundle.js"> </script>
|
||||
<script src="./swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
|
||||
// Build a system
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "http://petstore.swagger.io/v2/swagger.json",
|
||||
dom_id: '#swagger-ui',
|
||||
deepLinking: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":[],"names":[],"mappings":"","file":"swagger-ui.css","sourceRoot":""}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,70 @@
|
||||
"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);
|
||||
|
||||
for (var p in swaggerSettings) {
|
||||
if (swaggerSettings.hasOwnProperty(p)) {
|
||||
swaggerConfig[p] = swaggerSettings[p];
|
||||
}
|
||||
}
|
||||
window.ui = SwaggerUIBundle(swaggerConfig);
|
||||
}
|
||||
|
||||
window.onload = function () {
|
||||
initSwaggerUi();
|
||||
};
|
||||
|
||||
if (document.querySelector('.auth-wrapper .authorize')) {
|
||||
patchSwaggerUi();
|
||||
}
|
||||
else {
|
||||
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{ title }}</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
|
||||
</head>
|
||||
<body>
|
||||
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
|
||||
|
||||
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script>
|
||||
<script src="{% static 'drf-yasg/redoc-alpha/redoc.standalone.js' %}"> </script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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,64 +58,13 @@
|
||||
<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"
|
||||
};
|
||||
|
||||
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 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>
|
||||
|
||||
<div id="django-session-auth" class="hidden">
|
||||
{% if USE_SESSION_AUTH %}
|
||||
|
||||
+191
-285
@@ -1,17 +1,160 @@
|
||||
import inspect
|
||||
import logging
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.core.validators import RegexValidator
|
||||
from django.utils.encoding import force_text
|
||||
from rest_framework import serializers
|
||||
from rest_framework.mixins import RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin
|
||||
from rest_framework import serializers, status
|
||||
from rest_framework.mixins import DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from . import openapi
|
||||
from .errors import SwaggerGenerationError
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: used to forcibly remove the body of a request via :func:`.swagger_auto_schema`
|
||||
no_body = object()
|
||||
|
||||
|
||||
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,
|
||||
**extra_overrides):
|
||||
"""Decorate a view method to customize the :class:`.Operation` object generated from it.
|
||||
|
||||
`method` and `methods` are mutually exclusive and must only be present when decorating a view method that accepts
|
||||
more than one HTTP request method.
|
||||
|
||||
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
|
||||
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
|
||||
are mutually exclusive in an :class:`.Operation`. If you need to set custom ``form`` parameters, you can use
|
||||
the `manual_parameters` argument.
|
||||
|
||||
If a ``Serializer`` class or instance is given, it will be automatically converted into a :class:`.Schema`
|
||||
used as a ``body`` :class:`.Parameter`, or into a list of ``form`` :class:`.Parameter`\ s, as appropriate.
|
||||
|
||||
:param .Serializer query_serializer: if you use a ``Serializer`` to parse query parameters, you can pass it here
|
||||
and have :class:`.Parameter` objects be generated automatically from it.
|
||||
|
||||
If any ``Field`` on the serializer cannot be represented as a ``query`` :class:`.Parameter`
|
||||
(e.g. nested Serializers, file fields, ...), the schema generation will fail with an error.
|
||||
|
||||
Schema generation will also fail if the name of any Field on the `query_serializer` conflicts with parameters
|
||||
generated by ``filter_backends`` or ``paginator``.
|
||||
|
||||
:param list[.Parameter] manual_parameters: a list of manual parameters to override the automatically generated ones
|
||||
|
||||
:class:`.Parameter`\ s are identified by their (``name``, ``in``) combination, and any parameters given
|
||||
here will fully override automatically generated parameters if they collide.
|
||||
|
||||
It is an error to supply ``form`` parameters when the request does not consume form-data.
|
||||
|
||||
: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 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
|
||||
suppressed.
|
||||
|
||||
* if a plain string is given as value, a :class:`.Response` with no body and that string as its description
|
||||
will be generated
|
||||
* 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
|
||||
* a :class:`.Response` object will be used as-is; however if its ``schema`` attribute is a ``Serializer``,
|
||||
it will automatically be converted into a :class:`.Schema`
|
||||
|
||||
:param list[.FieldInspector] field_inspectors: extra serializer and field inspectors; these will be tried
|
||||
before :attr:`.ViewInspector.field_inspectors` on the :class:`.inspectors.SwaggerAutoSchema` instance
|
||||
:param list[.FilterInspector] filter_inspectors: extra filter inspectors; these will be tried before
|
||||
:attr:`.ViewInspector.filter_inspectors` on the :class:`.inspectors.SwaggerAutoSchema` instance
|
||||
:param list[.PaginatorInspector] paginator_inspectors: extra paginator inspectors; these will be tried before
|
||||
:attr:`.ViewInspector.paginator_inspectors` on the :class:`.inspectors.SwaggerAutoSchema` instance
|
||||
:param extra_overrides: extra values that will be saved into the ``overrides`` dict; these values will be available
|
||||
in the handling :class:`.inspectors.SwaggerAutoSchema` instance via ``self.overrides``
|
||||
"""
|
||||
|
||||
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,
|
||||
'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)
|
||||
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
|
||||
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 = [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 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"
|
||||
if method:
|
||||
_methods = [method.lower()]
|
||||
else:
|
||||
_methods = [mth.lower() for mth in methods]
|
||||
assert all(mth in available_methods for mth in _methods), "http method not bound to view"
|
||||
assert 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
|
||||
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"
|
||||
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, "swagger_auto_schema applied twice to method"
|
||||
view_method._swagger_auto_schema = data
|
||||
|
||||
return view_method
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def is_list_view(path, method, view):
|
||||
"""Check if the given path/method appears to represent a list view (as opposed to a detail/instance view).
|
||||
|
||||
@@ -32,7 +175,7 @@ def is_list_view(path, method, view):
|
||||
# a detail_route is surely not a list route
|
||||
return False
|
||||
|
||||
# for APIView, if it's a detail view it can't also be a list view
|
||||
# for GenericAPIView, if it's a detail view it can't also be a list view
|
||||
if isinstance(view, (RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin)):
|
||||
return False
|
||||
|
||||
@@ -45,284 +188,13 @@ def is_list_view(path, method, view):
|
||||
return True
|
||||
|
||||
|
||||
def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_body=None, query_serializer=None,
|
||||
manual_parameters=None, operation_description=None, responses=None):
|
||||
"""Decorate a view method to customize the :class:`.Operation` object generated from it.
|
||||
|
||||
`method` and `methods` are mutually exclusive and must only be present when decorating a view method that accepts
|
||||
more than one HTTP request method.
|
||||
|
||||
The `auto_schema` and `operation_description` arguments take precendence over view- or method-level values.
|
||||
|
||||
: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 .SwaggerAutoSchema auto_schema: custom class to use for generating the Operation object
|
||||
:param .Schema,.SchemaRef,.Serializer request_body: custom request body, or :data:`.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
|
||||
are mutually exclusive in an :class:`.Operation`. If you need to set custom ``form`` parameters, you can use
|
||||
the `manual_parameters` argument.
|
||||
|
||||
If a ``Serializer`` class or instance is given, it will be automatically converted into a :class:`.Schema`
|
||||
used as a ``body`` :class:`.Parameter`, or into a list of ``form`` :class:`.Parameter`\ s, as appropriate.
|
||||
|
||||
:param .Serializer query_serializer: if you use a ``Serializer`` to parse query parameters, you can pass it here
|
||||
and have :class:`.Parameter` objects be generated automatically from it.
|
||||
|
||||
If any ``Field`` on the serializer cannot be represented as a ``query`` :class:`.Parameter`
|
||||
(e.g. nested Serializers, file fields, ...), the schema generation will fail with an error.
|
||||
|
||||
Schema generation will also fail if the name of any Field on the `query_serializer` conflicts with parameters
|
||||
generated by ``filter_backends`` or ``paginator``.
|
||||
|
||||
:param list[.Parameter] manual_parameters: a list of manual parameters to override the automatically generated ones
|
||||
|
||||
:class:`.Parameter`\ s are identified by their (``name``, ``in``) combination, and any parameters given
|
||||
here will fully override automatically generated parameters if they collide.
|
||||
|
||||
It is an error to supply ``form`` parameters when the request does not consume form-data.
|
||||
|
||||
:param str operation_description: operation description override
|
||||
: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
|
||||
suppressed.
|
||||
|
||||
* if a plain string is given as value, a :class:`.Response` with no body and that string as its description
|
||||
will be generated
|
||||
* 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
|
||||
* a :class:`.Response` object will be used as-is; however if its ``schema`` attribute is a ``Serializer``,
|
||||
it will automatically be converted into a :class:`.Schema`
|
||||
|
||||
"""
|
||||
|
||||
def decorator(view_method):
|
||||
data = {
|
||||
'auto_schema': auto_schema,
|
||||
'request_body': request_body,
|
||||
'query_serializer': query_serializer,
|
||||
'manual_parameters': manual_parameters,
|
||||
'operation_description': operation_description,
|
||||
'responses': responses,
|
||||
}
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
|
||||
# if the method is a detail_route or list_route, 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', [])
|
||||
if bind_to_methods or http_method_names:
|
||||
# detail_route, list_route or api_view
|
||||
assert bool(http_method_names) != bool(bind_to_methods), "this should never happen"
|
||||
available_methods = http_method_names + bind_to_methods
|
||||
existing_data = getattr(view_method, 'swagger_auto_schema', {})
|
||||
|
||||
if http_method_names:
|
||||
_route = "api_view"
|
||||
else:
|
||||
_route = "detail_route" if view_method.detail else "list_route"
|
||||
|
||||
_methods = methods
|
||||
if len(available_methods) > 1:
|
||||
assert methods or method, \
|
||||
"on multi-method %s, you must specify swagger_auto_schema on a per-method basis " \
|
||||
"using one of the `method` or `methods` arguments" % _route
|
||||
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"
|
||||
if method:
|
||||
_methods = [method.lower()]
|
||||
else:
|
||||
_methods = [mth.lower() for mth in methods]
|
||||
assert not any(mth in existing_data for mth in _methods), "method defined multiple times"
|
||||
assert all(mth in available_methods for mth in _methods), "method not bound to %s" % _route
|
||||
|
||||
existing_data.update((mth.lower(), data) for mth in _methods)
|
||||
else:
|
||||
existing_data[available_methods[0]] = data
|
||||
view_method.swagger_auto_schema = existing_data
|
||||
else:
|
||||
assert method is None and methods is None, \
|
||||
"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"
|
||||
view_method.swagger_auto_schema = data
|
||||
|
||||
return view_method
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def serializer_field_to_swagger(field, swagger_object_type, definitions=None, **kwargs):
|
||||
"""Convert a drf Serializer or Field instance into a Swagger object.
|
||||
|
||||
:param rest_framework.serializers.Field field: the source field
|
||||
:param type[openapi.SwaggerDict] swagger_object_type: should be one of Schema, Parameter, Items
|
||||
:param .ReferenceResolver definitions: used to serialize Schemas by reference
|
||||
:param kwargs: extra attributes for constructing the object;
|
||||
if swagger_object_type is Parameter, ``name`` and ``in_`` should be provided
|
||||
:return: the swagger object
|
||||
:rtype: openapi.Parameter, openapi.Items, openapi.Schema
|
||||
"""
|
||||
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 = title if swagger_object_type == openapi.Schema else None # only Schema has title
|
||||
title = None
|
||||
description = force_text(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(**instance_kwargs):
|
||||
if swagger_object_type == openapi.Parameter:
|
||||
instance_kwargs['required'] = field.required
|
||||
if swagger_object_type != openapi.Items:
|
||||
default = getattr(field, 'default', serializers.empty)
|
||||
if default is not serializers.empty:
|
||||
instance_kwargs['default'] = default
|
||||
instance_kwargs.update(kwargs)
|
||||
return swagger_object_type(title=title, description=description, **instance_kwargs)
|
||||
|
||||
# arrays in Schema have Schema elements, arrays in Parameter and Items have Items elements
|
||||
ChildSwaggerType = openapi.Schema if swagger_object_type == openapi.Schema else openapi.Items
|
||||
|
||||
# ------ NESTED
|
||||
if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
|
||||
child_schema = serializer_field_to_swagger(field.child, ChildSwaggerType, definitions)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=child_schema,
|
||||
)
|
||||
elif isinstance(field, serializers.Serializer):
|
||||
if swagger_object_type != openapi.Schema:
|
||||
raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__)
|
||||
assert definitions is not None, "ReferenceResolver required when instantiating Schema"
|
||||
|
||||
serializer = field
|
||||
if hasattr(serializer, '__ref_name__'):
|
||||
ref_name = serializer.__ref_name__
|
||||
else:
|
||||
ref_name = type(serializer).__name__
|
||||
if ref_name.endswith('Serializer'):
|
||||
ref_name = ref_name[:-len('Serializer')]
|
||||
|
||||
def make_schema_definition():
|
||||
properties = OrderedDict()
|
||||
required = []
|
||||
for key, value in serializer.fields.items():
|
||||
properties[key] = serializer_field_to_swagger(value, ChildSwaggerType, definitions)
|
||||
if value.read_only:
|
||||
properties[key].read_only = value.read_only
|
||||
if value.required:
|
||||
required.append(key)
|
||||
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties=properties,
|
||||
required=required or None,
|
||||
)
|
||||
|
||||
if not ref_name:
|
||||
return make_schema_definition()
|
||||
|
||||
definitions.setdefault(ref_name, make_schema_definition)
|
||||
return openapi.SchemaRef(definitions, ref_name)
|
||||
elif isinstance(field, serializers.ManyRelatedField):
|
||||
child_schema = serializer_field_to_swagger(field.child_relation, ChildSwaggerType, definitions)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=child_schema,
|
||||
unique_items=True, # is this OK?
|
||||
)
|
||||
elif isinstance(field, serializers.RelatedField):
|
||||
# TODO: infer type for PrimaryKeyRelatedField?
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
# ------ CHOICES
|
||||
elif isinstance(field, serializers.MultipleChoiceField):
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=ChildSwaggerType(
|
||||
type=openapi.TYPE_STRING,
|
||||
enum=list(field.choices.keys())
|
||||
)
|
||||
)
|
||||
elif isinstance(field, serializers.ChoiceField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, enum=list(field.choices.keys()))
|
||||
# ------ BOOL
|
||||
elif isinstance(field, serializers.BooleanField):
|
||||
return SwaggerType(type=openapi.TYPE_BOOLEAN)
|
||||
# ------ NUMERIC
|
||||
elif isinstance(field, (serializers.DecimalField, serializers.FloatField)):
|
||||
# TODO: min_value max_value
|
||||
return SwaggerType(type=openapi.TYPE_NUMBER)
|
||||
elif isinstance(field, serializers.IntegerField):
|
||||
# TODO: min_value max_value
|
||||
return SwaggerType(type=openapi.TYPE_INTEGER)
|
||||
# ------ STRING
|
||||
elif isinstance(field, serializers.EmailField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_EMAIL)
|
||||
elif isinstance(field, serializers.RegexField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, pattern=find_regex(field))
|
||||
elif isinstance(field, serializers.SlugField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_SLUG, pattern=find_regex(field))
|
||||
elif isinstance(field, serializers.URLField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)
|
||||
elif isinstance(field, serializers.IPAddressField):
|
||||
format = {'ipv4': openapi.FORMAT_IPV4, 'ipv6': openapi.FORMAT_IPV6}.get(field.protocol, None)
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=format)
|
||||
elif isinstance(field, serializers.CharField):
|
||||
# TODO: min_length max_length (for all CharField subclasses above too)
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
elif isinstance(field, serializers.UUIDField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_UUID)
|
||||
# ------ DATE & TIME
|
||||
elif isinstance(field, serializers.DateField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_DATE)
|
||||
elif isinstance(field, serializers.DateTimeField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_DATETIME)
|
||||
# ------ OTHERS
|
||||
elif isinstance(field, serializers.FileField):
|
||||
# swagger 2.0 does not support specifics about file fields, so ImageFile gets no special treatment
|
||||
# OpenAPI 3.0 does support it, so a future implementation could handle this better
|
||||
err = SwaggerGenerationError("parameter of type file is supported only in a formData Parameter")
|
||||
if swagger_object_type != openapi.Parameter:
|
||||
raise err # pragma: no cover
|
||||
param = SwaggerType(type=openapi.TYPE_FILE)
|
||||
if param['in'] != openapi.IN_FORM:
|
||||
raise err # pragma: no cover
|
||||
return param
|
||||
elif isinstance(field, serializers.DictField) and swagger_object_type == openapi.Schema:
|
||||
child_schema = serializer_field_to_swagger(field.child, ChildSwaggerType, definitions)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
additional_properties=child_schema
|
||||
)
|
||||
|
||||
# TODO unhandled fields: TimeField DurationField HiddenField ModelField NullBooleanField? JSONField
|
||||
|
||||
# everything else gets string by default
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
|
||||
|
||||
def find_regex(regex_field):
|
||||
"""Given a ``Field``, look for a ``RegexValidator`` and try to extract its pattern and return it as a string.
|
||||
|
||||
:param serializers.Field regex_field: the field instance
|
||||
:return: the extracted pattern, or ``None``
|
||||
:rtype: str
|
||||
"""
|
||||
regex_validator = None
|
||||
for validator in regex_field.validators:
|
||||
if isinstance(validator, RegexValidator):
|
||||
if regex_validator is not None:
|
||||
# bail if multiple validators are found - no obvious way to choose
|
||||
return None # pragma: no cover
|
||||
regex_validator = validator
|
||||
|
||||
# regex_validator.regex should be a compiled re object...
|
||||
return getattr(getattr(regex_validator, 'regex', None), 'pattern', None)
|
||||
def guess_response_status(method):
|
||||
if method == 'post':
|
||||
return status.HTTP_201_CREATED
|
||||
elif method == 'delete':
|
||||
return status.HTTP_204_NO_CONTENT
|
||||
else:
|
||||
return status.HTTP_200_OK
|
||||
|
||||
|
||||
def param_list_to_odict(parameters):
|
||||
@@ -338,3 +210,37 @@ def param_list_to_odict(parameters):
|
||||
result = OrderedDict(((param.name, param.in_), param) for param in parameters)
|
||||
assert len(result) == len(parameters), "duplicate Parameters found"
|
||||
return result
|
||||
|
||||
|
||||
def filter_none(obj):
|
||||
"""Remove ``None`` values from tuples, lists or dictionaries. Return other objects as-is.
|
||||
|
||||
:param obj:
|
||||
:return: collection with ``None`` values removed
|
||||
"""
|
||||
if obj is None:
|
||||
return None
|
||||
new_obj = None
|
||||
if isinstance(obj, dict):
|
||||
new_obj = type(obj)((k, v) for k, v in obj.items() if k is not None and v is not None)
|
||||
if isinstance(obj, (list, tuple)):
|
||||
new_obj = type(obj)(v for v in obj if v is not None)
|
||||
if new_obj is not None and len(new_obj) != len(obj):
|
||||
return new_obj # pragma: no cover
|
||||
return obj
|
||||
|
||||
|
||||
def force_serializer_instance(serializer):
|
||||
"""Force `serializer` into a ``Serializer`` instance. If it is not a ``Serializer`` class or instance, raises
|
||||
an assertion error.
|
||||
|
||||
:param serializer: serializer class or instance
|
||||
:return: serializer instance
|
||||
"""
|
||||
if inspect.isclass(serializer):
|
||||
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
|
||||
return serializer()
|
||||
|
||||
assert isinstance(serializer, serializers.BaseSerializer), \
|
||||
"Serializer class or instance required, not %s" % type(serializer).__name__
|
||||
return serializer
|
||||
|
||||
+24
-14
@@ -10,15 +10,17 @@ from rest_framework.response import Response
|
||||
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 (
|
||||
SwaggerJSONRenderer, SwaggerYAMLRenderer, SwaggerUIRenderer, ReDocRenderer, OpenAPIRenderer,
|
||||
OpenAPIRenderer, ReDocAlphaRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
|
||||
)
|
||||
|
||||
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
|
||||
UI_RENDERERS = {
|
||||
'swagger': (SwaggerUIRenderer, ReDocRenderer),
|
||||
'redoc': (ReDocRenderer, SwaggerUIRenderer),
|
||||
'redoc-alpha': (ReDocAlphaRenderer, ReDocRenderer, SwaggerUIRenderer)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,18 +48,17 @@ def deferred_never_cache(view_func):
|
||||
return _wrapped_view_func
|
||||
|
||||
|
||||
def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, validators=None,
|
||||
def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None,
|
||||
generator_class=OpenAPISchemaGenerator,
|
||||
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: Required. Swagger API Info object
|
||||
: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
|
||||
@@ -69,6 +70,7 @@ def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, v
|
||||
_generator_class = generator_class
|
||||
_auth_classes = authentication_classes
|
||||
_perm_classes = permission_classes
|
||||
info = info or swagger_settings.DEFAULT_INFO
|
||||
validators = validators or []
|
||||
_spec_renderers = tuple(renderer.with_validators(validators) for renderer in SPEC_RENDERERS)
|
||||
|
||||
@@ -82,12 +84,23 @@ def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, v
|
||||
renderer_classes = _spec_renderers
|
||||
|
||||
def get(self, request, version='', format=None):
|
||||
generator = self.generator_class(info, version, url, patterns, urlconf)
|
||||
generator = self.generator_class(info, request.version or version or '', url, patterns, urlconf)
|
||||
schema = generator.get_schema(request, self.public)
|
||||
if schema is None:
|
||||
raise exceptions.PermissionDenied() # pragma: no cover
|
||||
return Response(schema)
|
||||
|
||||
@classmethod
|
||||
def apply_cache(cls, view, cache_timeout, cache_kwargs):
|
||||
"""Override this method to customize how caching is applied to the view.
|
||||
|
||||
Arguments described in :meth:`.as_cached_view`.
|
||||
"""
|
||||
view = vary_on_headers('Cookie', 'Authorization')(view)
|
||||
view = cache_page(cache_timeout, **cache_kwargs)(view)
|
||||
view = deferred_never_cache(view) # disable in-browser caching
|
||||
return view
|
||||
|
||||
@classmethod
|
||||
def as_cached_view(cls, cache_timeout=0, cache_kwargs=None, **initkwargs):
|
||||
"""
|
||||
@@ -102,10 +115,7 @@ def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, v
|
||||
cache_kwargs = cache_kwargs or {}
|
||||
view = cls.as_view(**initkwargs)
|
||||
if cache_timeout != 0:
|
||||
if not public:
|
||||
view = vary_on_headers('Cookie', 'Authorization')(view)
|
||||
view = cache_page(cache_timeout, **cache_kwargs)(view)
|
||||
view = deferred_never_cache(view) # disable in-browser caching
|
||||
view = cls.apply_cache(view, cache_timeout, cache_kwargs)
|
||||
elif cache_kwargs:
|
||||
warnings.warn("cache_kwargs ignored because cache_timeout is 0 (disabled)")
|
||||
return view
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Generated by Django 2.0 on 2017-12-05 04:05
|
||||
# Generated by Django 2.0 on 2017-12-23 09:07
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
@@ -8,6 +10,7 @@ class Migration(migrations.Migration):
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
@@ -15,12 +18,13 @@ class Migration(migrations.Migration):
|
||||
name='Article',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(help_text='Main article headline', max_length=255, unique=True)),
|
||||
('body', models.TextField(help_text='Article content', max_length=5000)),
|
||||
('slug', models.SlugField(blank=True, help_text='Unique URL slug identifying the article', unique=True)),
|
||||
('title', models.CharField(help_text='title model help_text', max_length=255, unique=True)),
|
||||
('body', models.TextField(help_text='article model help_text', max_length=5000)),
|
||||
('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)),
|
||||
('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)),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
@@ -7,5 +7,6 @@ class Article(models.Model):
|
||||
slug = models.SlugField(help_text="slug model help_text", unique=True, blank=True)
|
||||
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)
|
||||
|
||||
cover = models.ImageField(upload_to='article/original/', blank=True)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from rest_framework import serializers
|
||||
|
||||
from articles.models import Article
|
||||
@@ -5,17 +6,28 @@ from articles.models import Article
|
||||
|
||||
class ArticleSerializer(serializers.ModelSerializer):
|
||||
references = serializers.DictField(
|
||||
help_text="this is a really bad example",
|
||||
help_text=_("this is a really bad example"),
|
||||
child=serializers.URLField(help_text="but i needed to test these 2 fields somehow"),
|
||||
read_only=True,
|
||||
)
|
||||
uuid = serializers.UUIDField(help_text="should articles have UUIDs?")
|
||||
uuid = serializers.UUIDField(help_text="should articles have UUIDs?", read_only=True)
|
||||
cover_name = serializers.FileField(use_url=False, source='cover', read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Article
|
||||
fields = ('title', 'body', 'slug', 'date_created', 'date_modified', 'references', 'uuid')
|
||||
read_only_fields = ('date_created', 'date_modified')
|
||||
fields = ('title', 'author', 'body', 'slug', 'date_created', 'date_modified',
|
||||
'references', 'uuid', 'cover', 'cover_name')
|
||||
read_only_fields = ('date_created', 'date_modified',
|
||||
'references', 'uuid', 'cover_name')
|
||||
lookup_field = 'slug'
|
||||
extra_kwargs = {'body': {'help_text': 'body serializer help_text'}}
|
||||
extra_kwargs = {
|
||||
'body': {'help_text': 'body serializer help_text'},
|
||||
'author': {
|
||||
'default': serializers.CurrentUserDefault(),
|
||||
'help_text': _("The ID of the user that created this article; if none is provided, "
|
||||
"defaults to the currently logged in user.")
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class ImageUploadSerializer(serializers.Serializer):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import datetime
|
||||
|
||||
from django.utils.decorators import method_decorator
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import detail_route, list_route
|
||||
@@ -10,15 +11,58 @@ from rest_framework.response import Response
|
||||
|
||||
from articles import serializers
|
||||
from articles.models import Article
|
||||
from drf_yasg.inspectors import SwaggerAutoSchema
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.app_settings import swagger_settings
|
||||
from drf_yasg.inspectors import CoreAPICompatInspector, FieldInspector, NotHandled, SwaggerAutoSchema
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
|
||||
|
||||
class NoPagingAutoSchema(SwaggerAutoSchema):
|
||||
class DjangoFilterDescriptionInspector(CoreAPICompatInspector):
|
||||
def get_filter_parameters(self, filter_backend):
|
||||
if isinstance(filter_backend, DjangoFilterBackend):
|
||||
result = super(DjangoFilterDescriptionInspector, self).get_filter_parameters(filter_backend)
|
||||
for param in result:
|
||||
if not param.get('description', ''):
|
||||
param.description = "Filter the returned list by {field_name}".format(field_name=param.name)
|
||||
|
||||
return result
|
||||
|
||||
return NotHandled
|
||||
|
||||
|
||||
class NoSchemaTitleInspector(FieldInspector):
|
||||
def process_result(self, result, method_name, obj, **kwargs):
|
||||
# remove the `title` attribute of all Schema objects
|
||||
if isinstance(result, openapi.Schema.OR_REF):
|
||||
# traverse any references and alter the Schema object in place
|
||||
schema = openapi.resolve_ref(result, self.components)
|
||||
schema.pop('title', None)
|
||||
|
||||
# no ``return schema`` here, because it would mean we always generate
|
||||
# an inline `object` instead of a definition reference
|
||||
|
||||
# return back the same object that we got - i.e. a reference if we got a reference
|
||||
return result
|
||||
|
||||
|
||||
class NoTitleAutoSchema(SwaggerAutoSchema):
|
||||
field_inspectors = [NoSchemaTitleInspector] + swagger_settings.DEFAULT_FIELD_INSPECTORS
|
||||
|
||||
|
||||
class NoPagingAutoSchema(NoTitleAutoSchema):
|
||||
def should_page(self):
|
||||
return False
|
||||
|
||||
|
||||
class ArticlePagination(LimitOffsetPagination):
|
||||
default_limit = 5
|
||||
max_limit = 25
|
||||
|
||||
|
||||
@method_decorator(name='list', decorator=swagger_auto_schema(
|
||||
operation_description="description from swagger_auto_schema via method_decorator",
|
||||
filter_inspectors=[DjangoFilterDescriptionInspector]
|
||||
))
|
||||
class ArticleViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
ArticleViewSet class docstring
|
||||
@@ -37,14 +81,15 @@ class ArticleViewSet(viewsets.ModelViewSet):
|
||||
lookup_value_regex = r'[a-z0-9]+(?:-[a-z0-9]+)'
|
||||
serializer_class = serializers.ArticleSerializer
|
||||
|
||||
pagination_class = LimitOffsetPagination
|
||||
max_page_size = 5
|
||||
pagination_class = ArticlePagination
|
||||
filter_backends = (DjangoFilterBackend, OrderingFilter)
|
||||
filter_fields = ('title',)
|
||||
ordering_fields = ('date_modified',)
|
||||
ordering = ('username',)
|
||||
ordering_fields = ('date_modified', 'date_created')
|
||||
ordering = ('date_created',)
|
||||
|
||||
@swagger_auto_schema(auto_schema=NoPagingAutoSchema)
|
||||
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)
|
||||
|
||||
@@ -0,0 +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'
|
||||
|
||||
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))
|
||||
Binary file not shown.
+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,2 @@
|
||||
..[validation]
|
||||
-r ../requirements/testproj.txt
|
||||
File diff suppressed because one or more lines are too long
@@ -1,27 +0,0 @@
|
||||
# Generated by Django 2.0 on 2017-12-05 04:05
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('snippets', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='snippet',
|
||||
name='owner',
|
||||
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='snippets', to=settings.AUTH_USER_MODEL),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='snippet',
|
||||
name='code',
|
||||
field=models.TextField(help_text='code model help text'),
|
||||
),
|
||||
]
|
||||
@@ -1,21 +1,26 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from rest_framework import serializers
|
||||
|
||||
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
|
||||
from snippets.models import LANGUAGE_CHOICES, STYLE_CHOICES, Snippet
|
||||
|
||||
|
||||
class LanguageSerializer(serializers.Serializer):
|
||||
__ref_name__ = None
|
||||
|
||||
name = serializers.ChoiceField(
|
||||
choices=LANGUAGE_CHOICES, default='python', help_text='The name of the programming language')
|
||||
|
||||
class Meta:
|
||||
ref_name = None
|
||||
|
||||
|
||||
class ExampleProjectSerializer(serializers.Serializer):
|
||||
__ref_name__ = 'Project'
|
||||
|
||||
project_name = serializers.CharField(help_text='Name of the project')
|
||||
github_repo = serializers.CharField(required=True, help_text='Github repository of the project')
|
||||
|
||||
class Meta:
|
||||
ref_name = 'Project'
|
||||
|
||||
|
||||
class SnippetSerializer(serializers.Serializer):
|
||||
"""SnippetSerializer classdoc
|
||||
@@ -23,20 +28,35 @@ class SnippetSerializer(serializers.Serializer):
|
||||
create: docstring for create from serializer classdoc
|
||||
"""
|
||||
id = serializers.IntegerField(read_only=True, help_text="id serializer help text")
|
||||
owner = serializers.ReadOnlyField(source='owner.username')
|
||||
owner = serializers.PrimaryKeyRelatedField(
|
||||
queryset=get_user_model().objects.all(),
|
||||
default=serializers.CurrentUserDefault(),
|
||||
help_text="The ID of the user that created this snippet; if none is provided, "
|
||||
"defaults to the currently logged in user."
|
||||
)
|
||||
owner_as_string = serializers.PrimaryKeyRelatedField(
|
||||
help_text="The ID of the user that created this snippet.",
|
||||
pk_field=serializers.CharField(help_text="this help text should not show up"),
|
||||
read_only=True,
|
||||
source='owner',
|
||||
)
|
||||
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
|
||||
code = serializers.CharField(style={'base_template': 'textarea.html'})
|
||||
linenos = serializers.BooleanField(required=False)
|
||||
language = LanguageSerializer(help_text="Sample help text for language")
|
||||
styles = serializers.MultipleChoiceField(choices=STYLE_CHOICES, default=['friendly'])
|
||||
lines = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, allow_null=True, required=False)
|
||||
example_projects = serializers.ListSerializer(child=ExampleProjectSerializer())
|
||||
difficulty_factor = serializers.FloatField(help_text="this is here just to test FloatField")
|
||||
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)
|
||||
|
||||
def create(self, validated_data):
|
||||
"""
|
||||
Create and return a new `Snippet` instance, given the validated data.
|
||||
"""
|
||||
del validated_data['styles']
|
||||
del validated_data['lines']
|
||||
del validated_data['difficulty_factor']
|
||||
return Snippet.objects.create(**validated_data)
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
from django.conf.urls import url
|
||||
import django
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
url(r'$', views.SnippetList.as_view()),
|
||||
url(r'^(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
|
||||
]
|
||||
if django.VERSION[:2] >= (2, 0):
|
||||
from django.urls import path
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.SnippetList.as_view()),
|
||||
path('<int:pk>/', views.SnippetDetail.as_view()),
|
||||
]
|
||||
else:
|
||||
from django.conf.urls import url
|
||||
urlpatterns = [
|
||||
url('^$', views.SnippetList.as_view()),
|
||||
url(r'^(?P<pk>\d+)/$', views.SnippetDetail.as_view()),
|
||||
]
|
||||
|
||||
@@ -1,14 +1,30 @@
|
||||
from djangorestframework_camel_case.parser import CamelCaseJSONParser
|
||||
from djangorestframework_camel_case.render import CamelCaseJSONRenderer
|
||||
from inflection import camelize
|
||||
from rest_framework import generics
|
||||
|
||||
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
|
||||
|
||||
|
||||
class CamelCaseOperationIDAutoSchema(SwaggerAutoSchema):
|
||||
def get_operation_id(self, operation_keys):
|
||||
operation_id = super(CamelCaseOperationIDAutoSchema, self).get_operation_id(operation_keys)
|
||||
return camelize(operation_id, uppercase_first_letter=False)
|
||||
|
||||
|
||||
class SnippetList(generics.ListCreateAPIView):
|
||||
"""SnippetList classdoc"""
|
||||
queryset = Snippet.objects.all()
|
||||
serializer_class = SnippetSerializer
|
||||
|
||||
parser_classes = (CamelCaseJSONParser,)
|
||||
renderer_classes = (CamelCaseJSONRenderer,)
|
||||
swagger_schema = CamelCaseOperationIDAutoSchema
|
||||
|
||||
def perform_create(self, serializer):
|
||||
serializer.save(owner=self.request.user)
|
||||
|
||||
@@ -31,10 +47,22 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
serializer_class = SnippetSerializer
|
||||
pagination_class = None
|
||||
|
||||
parser_classes = (CamelCaseJSONParser,)
|
||||
renderer_classes = (CamelCaseJSONRenderer,)
|
||||
swagger_schema = CamelCaseOperationIDAutoSchema
|
||||
|
||||
def patch(self, request, *args, **kwargs):
|
||||
"""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
|
||||
)
|
||||
])
|
||||
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',
|
||||
@@ -69,16 +60,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,16 +78,21 @@ 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'
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
@@ -126,5 +112,59 @@ 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,
|
||||
'formatters': {
|
||||
'pipe_separated': {
|
||||
'format': '%(asctime)s | %(levelname)s | %(name)s | %(message)s'
|
||||
}
|
||||
},
|
||||
'handlers': {
|
||||
'console_log': {
|
||||
'level': 'DEBUG',
|
||||
'class': 'logging.StreamHandler',
|
||||
'stream': 'ext://sys.stdout',
|
||||
'formatter': 'pipe_separated',
|
||||
},
|
||||
},
|
||||
'loggers': {
|
||||
'drf_yasg': {
|
||||
'handlers': ['console_log'],
|
||||
'level': 'DEBUG',
|
||||
'propagate': False,
|
||||
},
|
||||
'django': {
|
||||
'handlers': ['console_log'],
|
||||
'level': 'DEBUG',
|
||||
'propagate': False,
|
||||
},
|
||||
'django.db.backends': {
|
||||
'handlers': ['console_log'],
|
||||
'level': 'INFO',
|
||||
'propagate': False,
|
||||
},
|
||||
'django.template': {
|
||||
'handlers': ['console_log'],
|
||||
'level': 'INFO',
|
||||
'propagate': False,
|
||||
},
|
||||
'swagger_spec_validator': {
|
||||
'handlers': ['console_log'],
|
||||
'level': 'INFO',
|
||||
'propagate': False,
|
||||
}
|
||||
},
|
||||
'root': {
|
||||
'handlers': ['console_log'],
|
||||
'level': 'INFO',
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
+40
-16
@@ -1,20 +1,29 @@
|
||||
from django.conf.urls import url, include
|
||||
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
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.views import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(
|
||||
openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
description="Test description",
|
||||
terms_of_service="https://www.google.com/policies/terms/",
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
),
|
||||
swagger_info = openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
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"),
|
||||
)
|
||||
|
||||
SchemaView = get_schema_view(
|
||||
validators=['ssv', 'flex'],
|
||||
public=True,
|
||||
permission_classes=(permissions.AllowAny,),
|
||||
@@ -26,13 +35,28 @@ 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)$', 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'),
|
||||
url(r'^cached/swagger(?P<format>.json|.yaml)$', schema_view.without_ui(cache_timeout=None), name='schema-json'),
|
||||
url(r'^cached/swagger/$', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'),
|
||||
url(r'^cached/redoc/$', schema_view.with_ui('redoc', cache_timeout=None), name='schema-redoc'),
|
||||
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
|
||||
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
|
||||
url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
|
||||
url(r'^redoc-alpha/$', SchemaView.with_ui('redoc-alpha', cache_timeout=0), name='schema-redoc-alpha'),
|
||||
url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'),
|
||||
url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'),
|
||||
url(r'^cached/redoc/$', SchemaView.with_ui('redoc', cache_timeout=None), name='cschema-redoc'),
|
||||
|
||||
url(r'^$', root_redirect),
|
||||
|
||||
url(r'^admin/', admin.site.urls),
|
||||
url(r'^snippets/', include('snippets.urls')),
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -6,14 +6,16 @@ from snippets.models import Snippet
|
||||
|
||||
class UserSerializerrr(serializers.ModelSerializer):
|
||||
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
|
||||
article_slugs = serializers.SlugRelatedField(read_only=True, slug_field='slug', many=True, source='articles')
|
||||
last_connected_ip = serializers.IPAddressField(help_text="i'm out of ideas", protocol='ipv4', read_only=True)
|
||||
last_connected_at = serializers.DateField(help_text="really?", read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('id', 'username', 'email', 'snippets', 'last_connected_ip', 'last_connected_at')
|
||||
fields = ('id', 'username', 'email', 'articles', 'snippets',
|
||||
'last_connected_ip', 'last_connected_at', 'article_slugs')
|
||||
|
||||
|
||||
class UserListQuerySerializer(serializers.Serializer):
|
||||
username = serializers.CharField(help_text="this field is generated from a query_serializer")
|
||||
is_staff = serializers.BooleanField(help_text="this one too!")
|
||||
username = serializers.CharField(help_text="this field is generated from a query_serializer", required=False)
|
||||
is_staff = serializers.BooleanField(help_text="this one too!", required=False)
|
||||
|
||||
@@ -4,5 +4,5 @@ from users import views
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^$', views.UserList.as_view()),
|
||||
url(r'^(?P<pk>[0-9]+)/$', views.user_detail),
|
||||
url(r'^(?P<pk>\d+)/$', views.user_detail),
|
||||
]
|
||||
|
||||
@@ -6,8 +6,8 @@ from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.utils import swagger_auto_schema, no_body
|
||||
from users.serializers import UserSerializerrr, UserListQuerySerializer
|
||||
from drf_yasg.utils import no_body, swagger_auto_schema
|
||||
from users.serializers import UserListQuerySerializer, UserSerializerrr
|
||||
|
||||
|
||||
class UserList(APIView):
|
||||
@@ -32,7 +32,7 @@ class UserList(APIView):
|
||||
serializer.save()
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
|
||||
@swagger_auto_schema(request_body=no_body, operation_description="dummy operation")
|
||||
@swagger_auto_schema(request_body=no_body, operation_id="users_dummy", operation_description="dummy operation")
|
||||
def patch(self, request):
|
||||
pass
|
||||
|
||||
|
||||
+44
-15
@@ -1,20 +1,30 @@
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from collections import OrderedDict
|
||||
|
||||
import pytest
|
||||
from ruamel import yaml
|
||||
from datadiff.tools import assert_equal
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework.test import APIRequestFactory
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from drf_yasg import openapi, codecs
|
||||
from drf_yasg import codecs, openapi
|
||||
from drf_yasg.codecs import yaml_sane_dump, yaml_sane_load
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def generator():
|
||||
return OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
)
|
||||
def mock_schema_request(db):
|
||||
from rest_framework.test import force_authenticate
|
||||
|
||||
factory = APIRequestFactory()
|
||||
user = User.objects.create_user(username='admin', is_staff=True, is_superuser=True)
|
||||
|
||||
request = factory.get('/swagger.json')
|
||||
force_authenticate(request, user=user)
|
||||
request = APIView().initialize_request(request)
|
||||
return request
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -28,19 +38,22 @@ def codec_yaml():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def swagger(generator):
|
||||
return generator.get_schema(None, True)
|
||||
def swagger(mock_schema_request):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
)
|
||||
return generator.get_schema(mock_schema_request, True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def swagger_dict(generator):
|
||||
swagger = generator.get_schema(None, True)
|
||||
json_bytes = codec_json().encode(swagger)
|
||||
return json.loads(json_bytes.decode('utf-8'))
|
||||
def swagger_dict(swagger, codec_json):
|
||||
json_bytes = codec_json.encode(swagger)
|
||||
return json.loads(json_bytes.decode('utf-8'), object_pairs_hook=OrderedDict)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def validate_schema():
|
||||
def validate_schema(db):
|
||||
def validate_schema(swagger):
|
||||
from flex.core import parse as validate_flex
|
||||
from swagger_spec_validator.validator20 import validate_spec as validate_ssv
|
||||
@@ -51,6 +64,22 @@ def validate_schema():
|
||||
return validate_schema
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def compare_schemas():
|
||||
def compare_schemas(schema1, schema2):
|
||||
schema1 = OrderedDict(schema1)
|
||||
schema2 = OrderedDict(schema2)
|
||||
ignore = ['info', 'host', 'schemes', 'basePath', 'securityDefinitions']
|
||||
for attr in ignore:
|
||||
schema1.pop(attr, None)
|
||||
schema2.pop(attr, None)
|
||||
|
||||
# print diff between YAML strings because it's prettier
|
||||
assert_equal(yaml_sane_dump(schema1, binary=False), yaml_sane_dump(schema2, binary=False))
|
||||
|
||||
return compare_schemas
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def swagger_settings(settings):
|
||||
swagger_settings = copy.deepcopy(settings.SWAGGER_SETTINGS)
|
||||
@@ -68,4 +97,4 @@ def redoc_settings(settings):
|
||||
@pytest.fixture
|
||||
def reference_schema():
|
||||
with open(os.path.join(os.path.dirname(__file__), 'reference.yaml')) as reference:
|
||||
return yaml.safe_load(reference)
|
||||
return yaml_sane_load(reference)
|
||||
|
||||
+99
-26
@@ -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
|
||||
@@ -16,11 +20,11 @@ paths:
|
||||
/articles/:
|
||||
get:
|
||||
operationId: articles_list
|
||||
description: ArticleViewSet class docstring
|
||||
description: description from swagger_auto_schema via method_decorator
|
||||
parameters:
|
||||
- name: title
|
||||
in: query
|
||||
description: ''
|
||||
description: Filter the returned list by title
|
||||
required: false
|
||||
type: string
|
||||
- name: ordering
|
||||
@@ -89,7 +93,7 @@ paths:
|
||||
parameters:
|
||||
- name: title
|
||||
in: query
|
||||
description: ''
|
||||
description: Filter the returned list by title
|
||||
required: false
|
||||
type: string
|
||||
- name: ordering
|
||||
@@ -178,6 +182,7 @@ paths:
|
||||
description: slug model help_text
|
||||
required: true
|
||||
type: string
|
||||
format: slug
|
||||
pattern: '[a-z0-9]+(?:-[a-z0-9]+)'
|
||||
/articles/{slug}/image/:
|
||||
get:
|
||||
@@ -231,6 +236,7 @@ paths:
|
||||
description: slug model help_text
|
||||
required: true
|
||||
type: string
|
||||
format: slug
|
||||
pattern: '[a-z0-9]+(?:-[a-z0-9]+)'
|
||||
/plain/:
|
||||
get:
|
||||
@@ -247,7 +253,7 @@ paths:
|
||||
parameters: []
|
||||
/snippets/:
|
||||
get:
|
||||
operationId: snippets_list
|
||||
operationId: snippetsList
|
||||
description: SnippetList classdoc
|
||||
parameters: []
|
||||
responses:
|
||||
@@ -262,7 +268,7 @@ paths:
|
||||
tags:
|
||||
- snippets
|
||||
post:
|
||||
operationId: snippets_create
|
||||
operationId: snippetsCreate
|
||||
description: post method docstring
|
||||
parameters:
|
||||
- name: data
|
||||
@@ -282,7 +288,7 @@ paths:
|
||||
parameters: []
|
||||
/snippets/{id}/:
|
||||
get:
|
||||
operationId: snippets_read
|
||||
operationId: snippetsRead
|
||||
description: SnippetDetail classdoc
|
||||
parameters: []
|
||||
responses:
|
||||
@@ -295,7 +301,7 @@ paths:
|
||||
tags:
|
||||
- snippets
|
||||
put:
|
||||
operationId: snippets_update
|
||||
operationId: snippetsUpdate
|
||||
description: put class docstring
|
||||
parameters:
|
||||
- name: data
|
||||
@@ -313,7 +319,7 @@ paths:
|
||||
tags:
|
||||
- snippets
|
||||
patch:
|
||||
operationId: snippets_partial_update
|
||||
operationId: snippetsPartialUpdate
|
||||
description: patch method docstring
|
||||
parameters:
|
||||
- name: data
|
||||
@@ -331,9 +337,14 @@ paths:
|
||||
tags:
|
||||
- snippets
|
||||
delete:
|
||||
operationId: snippets_delete
|
||||
operationId: snippetsDelete
|
||||
description: delete method docstring
|
||||
parameters: []
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: path parameter override
|
||||
required: true
|
||||
type: integer
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
@@ -355,12 +366,12 @@ paths:
|
||||
- name: username
|
||||
in: query
|
||||
description: this field is generated from a query_serializer
|
||||
required: true
|
||||
required: false
|
||||
type: string
|
||||
- name: is_staff
|
||||
in: query
|
||||
description: this one too!
|
||||
required: true
|
||||
required: false
|
||||
type: boolean
|
||||
responses:
|
||||
'200':
|
||||
@@ -402,7 +413,7 @@ paths:
|
||||
tags:
|
||||
- users
|
||||
patch:
|
||||
operationId: users_partial_update
|
||||
operationId: users_dummy
|
||||
description: dummy operation
|
||||
parameters: []
|
||||
responses:
|
||||
@@ -459,21 +470,27 @@ definitions:
|
||||
required:
|
||||
- title
|
||||
- body
|
||||
- references
|
||||
- uuid
|
||||
type: object
|
||||
properties:
|
||||
title:
|
||||
description: title model help_text
|
||||
type: string
|
||||
maxLength: 255
|
||||
author:
|
||||
description: The ID of the user that created this article; if none is provided,
|
||||
defaults to the currently logged in user.
|
||||
type: integer
|
||||
default: 1
|
||||
body:
|
||||
description: body serializer help_text
|
||||
type: string
|
||||
maxLength: 5000
|
||||
slug:
|
||||
description: slug model help_text
|
||||
type: string
|
||||
format: slug
|
||||
pattern: ^[-a-zA-Z0-9_]+$
|
||||
maxLength: 50
|
||||
date_created:
|
||||
type: string
|
||||
format: date-time
|
||||
@@ -489,48 +506,72 @@ definitions:
|
||||
description: but i needed to test these 2 fields somehow
|
||||
type: string
|
||||
format: uri
|
||||
readOnly: true
|
||||
uuid:
|
||||
description: should articles have UUIDs?
|
||||
type: string
|
||||
format: uuid
|
||||
readOnly: true
|
||||
cover:
|
||||
type: string
|
||||
readOnly: true
|
||||
format: uri
|
||||
cover_name:
|
||||
type: string
|
||||
readOnly: true
|
||||
Project:
|
||||
required:
|
||||
- project_name
|
||||
- github_repo
|
||||
- projectName
|
||||
- githubRepo
|
||||
type: object
|
||||
properties:
|
||||
project_name:
|
||||
projectName:
|
||||
title: Project name
|
||||
description: Name of the project
|
||||
type: string
|
||||
github_repo:
|
||||
githubRepo:
|
||||
title: Github repo
|
||||
description: Github repository of the project
|
||||
type: string
|
||||
Snippet:
|
||||
required:
|
||||
- code
|
||||
- language
|
||||
- example_projects
|
||||
- difficulty_factor
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: Id
|
||||
description: id serializer help text
|
||||
type: integer
|
||||
readOnly: true
|
||||
owner:
|
||||
title: Owner
|
||||
description: The ID of the user that created this snippet; if none is provided,
|
||||
defaults to the currently logged in user.
|
||||
type: integer
|
||||
default: 1
|
||||
ownerAsString:
|
||||
description: The ID of the user that created this snippet.
|
||||
type: string
|
||||
readOnly: true
|
||||
title: Owner as string
|
||||
title:
|
||||
title: Title
|
||||
type: string
|
||||
maxLength: 100
|
||||
code:
|
||||
title: Code
|
||||
type: string
|
||||
linenos:
|
||||
title: Linenos
|
||||
type: boolean
|
||||
language:
|
||||
title: Language
|
||||
description: Sample help text for language
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
title: Name
|
||||
description: The name of the programming language
|
||||
type: string
|
||||
enum:
|
||||
@@ -970,6 +1011,7 @@ definitions:
|
||||
- zephir
|
||||
default: python
|
||||
styles:
|
||||
title: Styles
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
@@ -1006,47 +1048,78 @@ definitions:
|
||||
default:
|
||||
- friendly
|
||||
lines:
|
||||
title: Lines
|
||||
type: array
|
||||
items:
|
||||
type: integer
|
||||
example_projects:
|
||||
exampleProjects:
|
||||
title: Example projects
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/definitions/Project'
|
||||
difficulty_factor:
|
||||
readOnly: true
|
||||
difficultyFactor:
|
||||
title: Difficulty factor
|
||||
description: this is here just to test FloatField
|
||||
type: number
|
||||
readOnly: true
|
||||
default: 6.9
|
||||
UserSerializerrr:
|
||||
required:
|
||||
- username
|
||||
- articles
|
||||
- snippets
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
title: ID
|
||||
type: integer
|
||||
readOnly: true
|
||||
username:
|
||||
title: Username
|
||||
description: Required. 150 characters or fewer. Letters, digits and @/./+/-/_
|
||||
only.
|
||||
type: string
|
||||
pattern: ^[\w.@+-]+$
|
||||
maxLength: 150
|
||||
email:
|
||||
title: Email address
|
||||
type: string
|
||||
format: email
|
||||
snippets:
|
||||
maxLength: 254
|
||||
articles:
|
||||
title: Articles
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
type: integer
|
||||
uniqueItems: true
|
||||
snippets:
|
||||
title: Snippets
|
||||
type: array
|
||||
items:
|
||||
type: integer
|
||||
uniqueItems: true
|
||||
last_connected_ip:
|
||||
title: Last connected ip
|
||||
description: i'm out of ideas
|
||||
type: string
|
||||
format: ipv4
|
||||
readOnly: true
|
||||
last_connected_at:
|
||||
title: Last connected at
|
||||
description: really?
|
||||
type: string
|
||||
format: date
|
||||
readOnly: true
|
||||
article_slugs:
|
||||
title: Article slugs
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
format: slug
|
||||
pattern: ^[-a-zA-Z0-9_]+$
|
||||
readOnly: true
|
||||
uniqueItems: true
|
||||
securityDefinitions:
|
||||
basic:
|
||||
type: basic
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
from drf_yasg import openapi
|
||||
|
||||
|
||||
def test_operation_docstrings(swagger_dict):
|
||||
users_list = swagger_dict['paths']['/users/']
|
||||
assert users_list['get']['description'] == "UserList cbv classdoc"
|
||||
assert users_list['post']['description'] == "apiview post description override"
|
||||
|
||||
users_detail = swagger_dict['paths']['/users/{id}/']
|
||||
assert users_detail['get']['description'] == "user_detail fbv docstring"
|
||||
assert users_detail['put']['description'] == "user_detail fbv docstring"
|
||||
|
||||
|
||||
def test_parameter_docstrings(swagger_dict):
|
||||
users_detail = swagger_dict['paths']['/users/{id}/']
|
||||
assert users_detail['get']['parameters'][0]['description'] == "test manual param"
|
||||
assert users_detail['put']['parameters'][0]['in'] == openapi.IN_BODY
|
||||
@@ -1,22 +0,0 @@
|
||||
def test_appropriate_status_codes(swagger_dict):
|
||||
snippets_list = swagger_dict['paths']['/snippets/']
|
||||
assert '200' in snippets_list['get']['responses']
|
||||
assert '201' in snippets_list['post']['responses']
|
||||
|
||||
snippets_detail = swagger_dict['paths']['/snippets/{id}/']
|
||||
assert '200' in snippets_detail['get']['responses']
|
||||
assert '200' in snippets_detail['put']['responses']
|
||||
assert '200' in snippets_detail['patch']['responses']
|
||||
assert '204' in snippets_detail['delete']['responses']
|
||||
|
||||
|
||||
def test_operation_docstrings(swagger_dict):
|
||||
snippets_list = swagger_dict['paths']['/snippets/']
|
||||
assert snippets_list['get']['description'] == "SnippetList classdoc"
|
||||
assert snippets_list['post']['description'] == "post method docstring"
|
||||
|
||||
snippets_detail = swagger_dict['paths']['/snippets/{id}/']
|
||||
assert snippets_detail['get']['description'] == "SnippetDetail classdoc"
|
||||
assert snippets_detail['put']['description'] == "put class docstring"
|
||||
assert snippets_detail['patch']['description'] == "patch method docstring"
|
||||
assert snippets_detail['delete']['description'] == "delete method docstring"
|
||||
@@ -1,29 +0,0 @@
|
||||
def test_appropriate_status_codes(swagger_dict):
|
||||
articles_list = swagger_dict['paths']['/articles/']
|
||||
assert '200' in articles_list['get']['responses']
|
||||
assert '201' in articles_list['post']['responses']
|
||||
|
||||
articles_detail = swagger_dict['paths']['/articles/{slug}/']
|
||||
assert '200' in articles_detail['get']['responses']
|
||||
assert '200' in articles_detail['put']['responses']
|
||||
assert '200' in articles_detail['patch']['responses']
|
||||
assert '204' in articles_detail['delete']['responses']
|
||||
|
||||
|
||||
def test_operation_docstrings(swagger_dict):
|
||||
articles_list = swagger_dict['paths']['/articles/']
|
||||
assert articles_list['get']['description'] == "ArticleViewSet class docstring"
|
||||
assert articles_list['post']['description'] == "ArticleViewSet class docstring"
|
||||
|
||||
articles_detail = swagger_dict['paths']['/articles/{slug}/']
|
||||
assert articles_detail['get']['description'] == "retrieve class docstring"
|
||||
assert articles_detail['put']['description'] == "update method docstring"
|
||||
assert articles_detail['patch']['description'] == "partial_update description override"
|
||||
assert articles_detail['delete']['description'] == "destroy method docstring"
|
||||
|
||||
articles_today = swagger_dict['paths']['/articles/today/']
|
||||
assert articles_today['get']['description'] == "ArticleViewSet class docstring"
|
||||
|
||||
articles_image = swagger_dict['paths']['/articles/{slug}/image/']
|
||||
assert articles_image['get']['description'] == "image GET description override"
|
||||
assert articles_image['post']['description'] == "image method docstring"
|
||||
@@ -0,0 +1,92 @@
|
||||
from six import StringIO
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import tempfile
|
||||
from collections import OrderedDict
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management import call_command
|
||||
|
||||
from drf_yasg.codecs import yaml_sane_load
|
||||
|
||||
|
||||
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):
|
||||
User.objects.create_superuser('admin', 'admin@admin.admin', 'blabla')
|
||||
|
||||
output = call_generate_swagger(format='yaml', api_url='http://test.local:8002/', user='admin')
|
||||
output_schema = yaml_sane_load(output)
|
||||
assert output_schema == reference_schema
|
||||
|
||||
|
||||
def test_non_public(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):
|
||||
output = call_generate_swagger()
|
||||
output_schema = json.loads(output, object_pairs_hook=OrderedDict)
|
||||
assert len(output_schema['paths']) > 0
|
||||
|
||||
|
||||
def silentremove(filename):
|
||||
try:
|
||||
os.remove(filename)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def test_file_output(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'
|
||||
json_file = prefix + name + '.json'
|
||||
other_file = prefix + name + '.txt'
|
||||
|
||||
try:
|
||||
# when called with output file nothing should be written to stdout
|
||||
assert call_generate_swagger(output_file=yaml_file) == ''
|
||||
assert call_generate_swagger(output_file=json_file) == ''
|
||||
assert call_generate_swagger(output_file=other_file) == ''
|
||||
|
||||
with pytest.raises(OSError):
|
||||
# a second call should fail because file exists
|
||||
call_generate_swagger(output_file=yaml_file)
|
||||
|
||||
# a second call with overwrite should still succeed
|
||||
assert call_generate_swagger(output_file=json_file, overwrite=True) == ''
|
||||
|
||||
with open(yaml_file) as f:
|
||||
content = f.read()
|
||||
# YAML is a superset of JSON - that means we have to check that
|
||||
# the file is really YAML and not just JSON parsed by the YAML parser
|
||||
with pytest.raises(ValueError):
|
||||
json.loads(content)
|
||||
output_yaml = yaml_sane_load(content)
|
||||
with open(json_file) as f:
|
||||
output_json = json.load(f, object_pairs_hook=OrderedDict)
|
||||
with open(other_file) as f:
|
||||
output_other = json.load(f, object_pairs_hook=OrderedDict)
|
||||
|
||||
assert output_yaml == output_json == output_other
|
||||
finally:
|
||||
silentremove(yaml_file)
|
||||
silentremove(json_file)
|
||||
silentremove(other_file)
|
||||
@@ -1,13 +1,48 @@
|
||||
from datadiff.tools import assert_equal
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
from drf_yasg.inspectors import FieldInspector, FilterInspector, PaginatorInspector, SerializerInspector
|
||||
|
||||
|
||||
def test_reference_schema(swagger_dict, reference_schema):
|
||||
# formatted better than pytest diff
|
||||
swagger_dict = dict(swagger_dict)
|
||||
reference_schema = dict(reference_schema)
|
||||
ignore = ['info', 'host', 'schemes', 'basePath', 'securityDefinitions']
|
||||
for attr in ignore:
|
||||
swagger_dict.pop(attr, None)
|
||||
reference_schema.pop(attr, None)
|
||||
def test_reference_schema(swagger_dict, reference_schema, compare_schemas):
|
||||
compare_schemas(swagger_dict, reference_schema)
|
||||
|
||||
assert_equal(swagger_dict, reference_schema)
|
||||
|
||||
class NoOpFieldInspector(FieldInspector):
|
||||
pass
|
||||
|
||||
|
||||
class NoOpSerializerInspector(SerializerInspector):
|
||||
pass
|
||||
|
||||
|
||||
class NoOpFilterInspector(FilterInspector):
|
||||
pass
|
||||
|
||||
|
||||
class NoOpPaginatorInspector(PaginatorInspector):
|
||||
pass
|
||||
|
||||
|
||||
def test_noop_inspectors(swagger_settings, mock_schema_request, codec_json, reference_schema, compare_schemas):
|
||||
from drf_yasg import app_settings
|
||||
|
||||
def set_inspectors(inspectors, setting_name):
|
||||
inspectors = [__name__ + '.' + inspector.__name__ for inspector in inspectors]
|
||||
swagger_settings[setting_name] = inspectors + app_settings.SWAGGER_DEFAULTS[setting_name]
|
||||
|
||||
set_inspectors([NoOpFieldInspector, NoOpSerializerInspector], 'DEFAULT_FIELD_INSPECTORS')
|
||||
set_inspectors([NoOpFilterInspector], 'DEFAULT_FILTER_INSPECTORS')
|
||||
set_inspectors([NoOpPaginatorInspector], 'DEFAULT_PAGINATOR_INSPECTORS')
|
||||
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
)
|
||||
swagger = generator.get_schema(mock_schema_request, True)
|
||||
|
||||
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)
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
|
||||
import pytest
|
||||
from ruamel import yaml
|
||||
|
||||
from drf_yasg import openapi, codecs
|
||||
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
|
||||
|
||||
|
||||
def test_schema_generates_without_errors(generator):
|
||||
generator.get_schema(None, True)
|
||||
|
||||
|
||||
def test_schema_is_valid(generator, codec_yaml):
|
||||
swagger = generator.get_schema(request=None, public=False)
|
||||
def test_schema_is_valid(swagger, codec_yaml):
|
||||
codec_yaml.encode(swagger)
|
||||
|
||||
|
||||
def test_invalid_schema_fails(codec_json):
|
||||
def test_invalid_schema_fails(codec_json, mock_schema_request):
|
||||
# noinspection PyTypeChecker
|
||||
bad_generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(
|
||||
@@ -26,41 +23,47 @@ def test_invalid_schema_fails(codec_json):
|
||||
version="v2",
|
||||
)
|
||||
|
||||
swagger = bad_generator.get_schema(None, True)
|
||||
swagger = bad_generator.get_schema(mock_schema_request, True)
|
||||
with pytest.raises(codecs.SwaggerValidationError):
|
||||
codec_json.encode(swagger)
|
||||
|
||||
|
||||
def test_json_codec_roundtrip(codec_json, generator, validate_schema):
|
||||
swagger = generator.get_schema(None, True)
|
||||
def test_json_codec_roundtrip(codec_json, swagger, validate_schema):
|
||||
json_bytes = codec_json.encode(swagger)
|
||||
validate_schema(json.loads(json_bytes.decode('utf-8')))
|
||||
|
||||
|
||||
def test_yaml_codec_roundtrip(codec_yaml, generator, validate_schema):
|
||||
swagger = generator.get_schema(None, True)
|
||||
def test_yaml_codec_roundtrip(codec_yaml, swagger, validate_schema):
|
||||
yaml_bytes = codec_yaml.encode(swagger)
|
||||
assert b'omap' not in yaml_bytes # ensure no ugly !!omap is outputted
|
||||
assert b'&id' not in yaml_bytes and b'*id' not in yaml_bytes # ensure no YAML references are generated
|
||||
validate_schema(yaml.safe_load(yaml_bytes.decode('utf-8')))
|
||||
validate_schema(yaml_sane_load(yaml_bytes.decode('utf-8')))
|
||||
|
||||
|
||||
def test_yaml_and_json_match(codec_yaml, codec_json, generator):
|
||||
swagger = generator.get_schema(None, True)
|
||||
yaml_schema = yaml.safe_load(codec_yaml.encode(swagger).decode('utf-8'))
|
||||
json_schema = json.loads(codec_json.encode(swagger).decode('utf-8'))
|
||||
def test_yaml_and_json_match(codec_yaml, codec_json, swagger):
|
||||
yaml_schema = yaml_sane_load(codec_yaml.encode(swagger).decode('utf-8'))
|
||||
json_schema = json.loads(codec_json.encode(swagger).decode('utf-8'), object_pairs_hook=OrderedDict)
|
||||
assert yaml_schema == json_schema
|
||||
|
||||
|
||||
def test_basepath_only():
|
||||
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(None, public=True)
|
||||
assert 'host' not in swagger
|
||||
assert 'schemes' not in swagger
|
||||
assert swagger['basePath'] == '/' # base path is not implemented for now
|
||||
swagger = generator.get_schema(mock_schema_request, public=True)
|
||||
assert 'host' not in swagger and 'schemes' not in swagger
|
||||
assert swagger['info']['version'] == 'v2'
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
def test_paths_not_empty(swagger_dict):
|
||||
assert len(swagger_dict['paths']) > 0
|
||||
@@ -2,7 +2,8 @@ import json
|
||||
from collections import OrderedDict
|
||||
|
||||
import pytest
|
||||
from ruamel import yaml
|
||||
|
||||
from drf_yasg.codecs import yaml_sane_load
|
||||
|
||||
|
||||
def _validate_text_schema_view(client, validate_schema, path, loader):
|
||||
@@ -22,10 +23,10 @@ def test_swagger_json(client, validate_schema):
|
||||
|
||||
|
||||
def test_swagger_yaml(client, validate_schema):
|
||||
_validate_text_schema_view(client, validate_schema, "/swagger.yaml", yaml.safe_load)
|
||||
_validate_text_schema_view(client, validate_schema, "/swagger.yaml", yaml_sane_load)
|
||||
|
||||
|
||||
def test_exception_middleware(client, swagger_settings):
|
||||
def test_exception_middleware(client, swagger_settings, db):
|
||||
swagger_settings['SECURITY_DEFINITIONS'] = {
|
||||
'bad': {
|
||||
'bad_attribute': 'should not be accepted'
|
||||
@@ -51,10 +52,7 @@ def test_caching(client, validate_schema):
|
||||
prev_schema = None
|
||||
|
||||
for i in range(3):
|
||||
_validate_ui_schema_view(client, '/cached/redoc/', 'redoc/redoc.min.js')
|
||||
_validate_text_schema_view(client, validate_schema, '/cached/redoc/?format=openapi', json.loads)
|
||||
_validate_ui_schema_view(client, '/cached/swagger/', 'swagger-ui-dist/swagger-ui-bundle.js')
|
||||
_validate_text_schema_view(client, validate_schema, '/cached/swagger/?format=openapi', json.loads)
|
||||
_validate_text_schema_view(client, validate_schema, '/cached/swagger.yaml', yaml_sane_load)
|
||||
|
||||
json_schema = client.get('/cached/swagger.json')
|
||||
assert json_schema.status_code == 200
|
||||
@@ -70,5 +68,5 @@ def test_caching(client, validate_schema):
|
||||
@pytest.mark.urls('urlconfs.non_public_urls')
|
||||
def test_non_public(client):
|
||||
response = client.get('/private/swagger.yaml')
|
||||
swagger = yaml.safe_load(response.content.decode('utf-8'))
|
||||
swagger = yaml_sane_load(response.content.decode('utf-8'))
|
||||
assert len(swagger['paths']) == 0
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user