Compare commits

...

64 Commits

Author SHA1 Message Date
Cristi Vîjdea d2cc0a348c Adjust dummy version 2018-12-23 19:29:07 +02:00
Cristi Vîjdea f020cbd99e Add 1.12.0 changelog 2018-12-23 19:17:25 +02:00
Cristi Vîjdea 68400386d3 Update swagger-ui to 3.20.4 2018-12-23 18:44:31 +02:00
Cristi Vîjdea 7ce62616d2 Re-add test for DELETE form param 2018-12-23 18:28:13 +02:00
Cristi Vîjdea bebcc982e6 Call APIView get_ methods instead of direct attribute access
queryset -> get_queryset
renderer_classes -> get_renderers
parser_classes -> get_parsers
2018-12-23 18:19:45 +02:00
Cristi Vîjdea 04d61b9d97 Log errors details of SwaggerValidationError 2018-12-23 15:33:55 +02:00
Cristi Vîjdea b15535995f Add assertion against TYPE_ARRAY with no items 2018-12-23 15:32:06 +02:00
Cristi Vîjdea dd5965fa92 Fix tuple types in sphinx docstrings 2018-12-21 18:18:58 +02:00
Cristi Vîjdea bfd13668cc Fix deprecation warnings 2018-12-21 16:07:48 +02:00
Cristi Vîjdea 01391ca9eb Remove comment links to Django 1.11 docs 2018-12-21 15:55:23 +02:00
Cristi Vîjdea 86ac276449 Fix some version constraints 2018-12-21 15:55:03 +02:00
Cristi Vîjdea 66026d3483 Fix lint errors 2018-12-21 15:07:38 +02:00
Cristi Vîjdea db61c39ab1 Fix union types in sphinx docstrings 2018-12-21 15:04:25 +02:00
Cristi Vîjdea f77672875d Add /admin/ and /o/ urls to test urlconfs 2018-12-21 12:58:41 +02:00
Cristi Vîjdea 8057ce7a4a Detect missing setuptools-scm in setup.py 2018-12-21 12:44:27 +02:00
Cristi Vîjdea 3b31c54b9e Add get_security_definitions and get_security_requirements hooks 2018-12-21 12:40:45 +02:00
Cristi Vîjdea de950461c7 Fix absolute urls for swagger-ui oauth settings 2018-12-21 12:40:31 +02:00
Cristi Vîjdea 9d933a9745 Really fix django-oauth-toolkit version
This is the simplest way to keep all test configurations happy...

ref 85db6c9d79
2018-12-21 02:13:59 +02:00
Cristi Vîjdea a9ec14620c Fix security definitions ordering consistency 2018-12-21 02:04:15 +02:00
Cristi Vîjdea 5418415300 Remove bad NoneType usage 2018-12-21 01:39:29 +02:00
Cristi Vîjdea 494d422bf4 Update swagger-ui to 3.20.3 2018-12-21 01:36:37 +02:00
Cristi Vîjdea 85db6c9d79 Fix django-oauth-toolkit python version dependency
django-oauth-toolkit 1.1 is the last version to support Python 2.7/Django 1.11

Source: https://github.com/jazzband/django-oauth-toolkit/issues/579
2018-12-21 01:31:05 +02:00
Cristi Vîjdea b385228f7d Add mock OAuth2 provider to testproj 2018-12-21 01:07:11 +02:00
Cristi Vîjdea bbed2acf06 Handle lazy() proxies in user-supplied objects 2018-12-21 01:07:10 +02:00
Cristi Vîjdea 0c38c30020 Fix extra quotes in docs 2018-12-21 01:07:10 +02:00
Cristi Vîjdea a7d3066677 Create testproj default user in data migration 2018-12-21 01:07:10 +02:00
Cristi Vîjdea e98876bb38 Fix import errors in quickstart
Fixes #277.
Closes #278.
Fixes #279.
2018-12-19 23:51:53 +02:00
Cristi Vîjdea 8974aa5734 Merge pull request #276 from axnsan12/pyproject-pep518
Add pyproject.toml (implement PEP517 and PEP518)
2018-12-19 23:49:55 +02:00
Cristi Vîjdea 5652d2a04d Manually install setuptools-scm for Travis deploy
This only works because we still mostly use default build configuration of setuptools and wheel, so we don't really depend on PEP517 builds, only PEP518 build requirements.
2018-12-19 22:19:24 +02:00
Cristi Vîjdea cf4106f8f7 Use twine check instead of setup.py check 2018-12-19 21:46:49 +02:00
Cristi Vîjdea a24070446a Also update setuptools with pip 2018-12-19 21:46:49 +02:00
Cristi Vîjdea 1fc454fcfa Enable isolated_build for tox
This enables tox support for PEP517 and PEP518.
2018-12-19 21:46:48 +02:00
Cristi Vîjdea 789f118532 Update Heroku runtime to Python 3.7.1 2018-12-19 20:30:02 +02:00
Cristi Vîjdea 1946a1204d Remove requirements/setup.txt and setup_requires 2018-12-19 20:29:42 +02:00
Cristi Vîjdea 930f3825d7 Improve installation walkthroughs 2018-12-19 20:22:06 +02:00
Cristi Vîjdea dfd2bcabf2 Add build-system requirements to pyproject.toml
PEP518 added an alternative way to specify setup_requires before executing the setup.py script.
2018-12-19 20:22:06 +02:00
Cristi Vîjdea 4e4cd75fc4 Remove redundant getattr 2018-12-19 20:22:05 +02:00
Cristi Vîjdea 7548a42a9b Add empty pyproject.toml
Apparently this fixes `pip install -e .`?!?
https://stackoverflow.com/a/53698424/3194671
2018-12-19 20:22:05 +02:00
Cristi Vîjdea e182ab65ea Add x-nullable to paginator response fields
Closes #263.
2018-12-19 20:22:05 +02:00
Cristi Vîjdea f8e9fd6327 Prefix localStorage keys with current pathname
This avoids collisions between multiple instance of drf-yasg on the same domain.

Fixes #269.
2018-12-19 19:15:38 +02:00
unloder f66c8e83e6 Use list instead of tuple for argparse options (#275)
Aparently pycharm has a problem with tuples?
2018-12-19 18:57:49 +02:00
Cristi Vîjdea c5d4e6ca53 Do not generate form parameters for read_only serializer fields
Fixes #261.
2018-12-19 03:22:43 +02:00
Cristi Vîjdea eeb1bba9e7 Refactor summary and description processing
Merge get_summary and get_description into get_summary_and_description.
2018-12-19 03:05:32 +02:00
Cristi Vîjdea 852742baa9 Remove bad test case 2018-12-12 16:43:19 +02:00
Cristi Vîjdea 5b07b9dd40 Ignore exit status of coverage combine 2018-12-12 15:01:58 +02:00
Cristi Vîjdea 306e53461d Fix lint errors 2018-12-12 15:01:58 +02:00
Cristi Vîjdea 1d9387d8e5 Fix test name description 2018-12-12 12:46:04 +02:00
Cristi Vîjdea 1f95f4098b Don't allow form parameters with non-form consumes
Closes #270.
2018-12-12 12:43:33 +02:00
Cristi Vîjdea acfb0c5442 Remove default xdist argument to pytest 2018-12-12 12:21:16 +02:00
Cristi Vîjdea 543a1ade5e Test with Django REST Framework 3.9 2018-12-11 23:25:16 +02:00
Vitali Fokin f415a96aa6 Tags override support (#259) 2018-12-11 20:13:37 +02:00
Alexander Egorov c52daaea8c Fix incorrect return from _UIRenderer.render (#268) 2018-12-11 20:12:38 +02:00
Alexander Egorov f6544654ab Add enum type inference based on choices values (#264) 2018-12-07 14:11:13 +02:00
Cristi Vîjdea f587785eb4 Update Heroku python version 2018-11-29 02:39:32 +02:00
Cristi Vîjdea 161a2e1b89 Ignore schizophrenic flake8 error 2018-11-29 02:24:03 +02:00
Cristi Vîjdea a2bf515cc9 Revert "Fix lint errors"
This reverts commit 9f60dc191a.
2018-11-29 02:23:31 +02:00
Cristi Vîjdea 10a32f977c Add 1.11.1 changelog 2018-11-29 02:18:58 +02:00
Cristi Vîjdea 6b5022cd7d Use some more coreschema attributes in CoreAPICompatInspector
Closes #212.
Closes #233.
2018-11-29 02:12:32 +02:00
Cristi Vîjdea 708e70a526 Use collectionFormat=multi for MultiChoiceField in query and formData
Fixes #257.
2018-11-29 01:38:40 +02:00
Cristi Vîjdea 9f60dc191a Fix lint errors 2018-11-29 01:27:27 +02:00
Cristi Vîjdea a2b35f3363 Update swagger-ui to 3.20.1 and ReDoc to 2.0.0-alpha.41 2018-11-29 01:22:49 +02:00
Cristi Vîjdea 754ec8a779 Enable minLength and maxLength for ListSerializer 2018-11-29 00:32:31 +02:00
Randall Wang 3cd93bd572 Fix typo (#252) 2018-11-16 13:53:19 +02:00
Cristi Vîjdea c5f6a79cc8 Fix heroku build 2018-10-14 21:44:32 +03:00
72 changed files with 995 additions and 462 deletions
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<codeStyleSettings language="Python">
<option name="SOFT_MARGINS" value="120" />
</codeStyleSettings>
</code_scheme>
</component>
+5
View File
@@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>
+2
View File
@@ -16,6 +16,8 @@
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/testproj" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.cache" />
<excludeFolder url="file://$MODULE_DIR$/.eggs" />
<excludeFolder url="file://$MODULE_DIR$/.pytest_cache" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>
-5
View File
@@ -55,11 +55,6 @@
</option>
</inspection_tool>
<inspection_tool class="PyShadowingNamesInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="PyUnusedLocalInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false">
<option name="ignoreTupleUnpacking" value="true" />
<option name="ignoreLambdaParameters" value="true" />
<option name="ignoreLoopIterationVariables" value="true" />
</inspection_tool>
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
+10 -7
View File
@@ -15,18 +15,20 @@ jobs:
python: '3.7'
dist: xenial
sudo: required
-
python: '3.6'
- python: '3.6'
env: TOXENV=djmaster
- # readthedocs uses python 3.5 for building
python: '3.5'
env: TOXENV=docs
-
python: '3.6'
- python: '3.6'
env: TOXENV=lint
- stage: publish
python: '3.6'
before_script:
# workaround for Travis' inability to build PEP517 projects; anything added to build-system.requires
# will also have to be added here until Travis implements this
- pip install setuptools-scm
script: skip
env: PYPI_DEPLOY=true
deploy: &pypi
@@ -45,13 +47,14 @@ jobs:
fast_finish: true
install:
- pip install -r requirements/ci.txt
- python -m pip install -U pip setuptools
- pip install -r requirements/ci.txt
before_script:
- coverage erase
- coverage erase
script:
- tox
- tox
after_success:
- |
+6 -5
View File
@@ -35,6 +35,7 @@ You want to contribute some code? Great! Here are a few steps to get you started
$ virtualenv venv
$ source venv/bin/activate
(venv) $ python -m pip install -U pip setuptools
(venv) $ pip install -U -e .[validation]
(venv) $ pip install -U -r requirements/dev.txt
@@ -44,7 +45,6 @@ You want to contribute some code? Great! Here are a few steps to get you started
(venv) $ cd testproj
(venv) $ python manage.py migrate
(venv) $ python manage.py shell -c "import createsuperuser"
(venv) $ python manage.py runserver
(venv) $ firefox localhost:8000/swagger/
@@ -57,8 +57,7 @@ You want to contribute some code? Great! Here are a few steps to get you started
.. code:: console
(venv) $ cd testproj
(venv) $ python manage.py generate_swagger ../tests/reference.yaml --overwrite --user admin --url http://test.local:8002/
(venv) $ python testproj/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.
@@ -67,11 +66,13 @@ You want to contribute some code? Great! Here are a few steps to get you started
.. code:: console
# install test dependencies
(venv) $ pip install -U -r requirements/test.txt
# run tests in the current environment, faster than tox
(venv) $ pytest -n auto --cov
# (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
+1
View File
@@ -1,5 +1,6 @@
include README.rst
include LICENSE.rst
include pyproject.toml
recursive-include requirements *
recursive-include src/drf_yasg/static *
recursive-include src/drf_yasg/templates *
+1 -1
View File
@@ -1,2 +1,2 @@
release: python testproj/manage.py migrate && python testproj/manage.py shell -c "import createsuperuser"
release: python testproj/manage.py migrate
web: gunicorn --chdir testproj testproj.wsgi --log-file -
+3 -3
View File
@@ -114,6 +114,7 @@ In ``urls.py``:
.. code:: python
...
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
@@ -128,7 +129,6 @@ In ``urls.py``:
contact=openapi.Contact(email="contact@snippets.local"),
license=openapi.License(name="BSD License"),
),
validators=['flex', 'ssv'],
public=True,
permission_classes=(permissions.AllowAny,),
)
@@ -140,7 +140,7 @@ In ``urls.py``:
...
]
This exposes 4 cached, validated and publicly available endpoints:
This exposes 4 endpoints:
* A JSON view of your API specification at ``/swagger.json``
* A YAML view of your API specification at ``/swagger.yaml``
@@ -294,9 +294,9 @@ For additional usage examples, you can take a look at the test project in the ``
$ virtualenv venv
$ source venv/bin/activate
(venv) $ cd testproj
(venv) $ python -m pip install -U pip setuptools
(venv) $ pip install -U -r requirements.txt
(venv) $ python manage.py migrate
(venv) $ python manage.py shell -c "import createsuperuser"
(venv) $ python manage.py runserver
(venv) $ firefox localhost:8000/swagger/
+2 -2
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
set -ex
set -e
coverage combine
coverage combine || true
coverage report
codecov
+46
View File
@@ -2,6 +2,52 @@
Changelog
#########
**********
**1.12.0**
**********
*Release date: Dec 23, 2018*
- **ADDED:** ``get_security_definitions`` and ``get_security_requirements`` hooks to ``OpenAPISchemaGenerator``
- **ADDED:** added ``get_summary_and_description`` and ``split_summary_from_description`` extension points to
``SwaggerAutoSchema`` to allow for better customisation
- **IMPROVED:** updated ``swagger-ui`` to version 3.20.4
- **IMPROVED:** paginator ``next`` and ``previous`` fields are now marked as ``x-nullable`` (:issue:`263`)
- **IMPROVED:** added the ``tags`` argument to ``swagger_auto_schema`` (:pr:`259`)
- **IMPROVED:** type of ``enum`` will now be automatically detected from ``ChoiceField`` if all ``choices`` values
are objects of the same Python class (:pr:`264`)
- **IMPROVED:** ``SwaggerValidationError`` details will now be logged and shown in the exception message
- **FIXED:** user implementations of ``get_queryset``, ``get_parsers`` and ``get_renderers`` will no longer be bypassed
- **FIXED:** fixed handling of lazy objects in user-supplied values
- **FIXED:** ``read_only`` serializer fields will be correctly ignored when generating form parameters (:issue:`261`)
- **FIXED:** fixed incorrect return type from ``UIRenderer`` (:pr:`268`)
- **FIXED:** fixed incosistent ordering of global ``securityDefinitions`` and ``security`` objects
- **DEPRECATED:** the ``get_summary`` and ``get_description`` extension points have been deprecated in favor of the
new ``get_summary_and_description``, and will be removed in a future release
**IMPORTANT PACKAGING NOTE**
Starting with this version, the ``setup_requires`` argument was dropped from ``setup.py`` in favor of
``build-system.requires`` in ``pyproject.toml`` . This means that for correctly building or installing from sdist,
you will need to use a PEP517/PEP518 compliant tool (tox>=3.3.0, setuptools>=40, pip>=10.0, pep517.build) or manually
install the build requirements yourself (just ```setuptools`` and ``setuptools-scm``, for now).
Additionally, for correct package version detection, a full git checkout is required when building (this was always the
case). Building without ``.git`` or without ``setuptools-scm`` will result in a distribution with a version like
``drf-yasg-1!0.0.0.dev0+noscm.00000167d19bd859``.
**********
**1.11.1**
**********
*Release date: Nov 29, 2018*
- **IMPROVED:** updated ``swagger-ui`` to version 3.20.1
- **IMPROVED:** updated ``ReDoc`` to version 2.0.0-alpha.41
- **FIXED:** ``minLength`` and ``maxLength`` will now also work for ``ListSerializer`` in addition to ``ListField``
- **FIXED:** ``MultipleChoiceField`` will now use the ``multi`` ``collectionFormat`` where appropriate (:issue:`257`)
- **FIXED:** the ``format``, ``pattern``, ``enum``, ``min_length`` and ``max_length`` attributes of
``coreschema.Schema`` will now be persited into the converted ``openapi.Parameter`` (:issue:`212`, :pr:`233`)
**********
**1.11.0**
+4 -1
View File
@@ -171,16 +171,19 @@ nitpick_ignore = [
('py:class', 'int'),
('py:class', 'bytes'),
('py:class', 'tuple'),
('py:class', 'callable'),
('py:class', 'function'),
('py:class', 'type'),
('py:class', 'OrderedDict'),
('py:class', 'None'),
('py:obj', 'None'),
('py:class', 'Exception'),
('py:class', 'collections.OrderedDict'),
('py:class', 'ruamel.yaml.dumper.SafeDumper'),
('py:class', 'rest_framework.serializers.Serializer'),
('py:class', 'rest_framework.renderers.BaseRenderer'),
('py:class', 'rest_framework.parsers.BaseParser'),
('py:class', 'rest_framework.schemas.generators.EndpointEnumerator'),
('py:class', 'rest_framework.views.APIView'),
+1 -1
View File
@@ -314,7 +314,7 @@ implemented like so:
))
class ArticleViewSet(viewsets.ModelViewSet):
filter_backends = (DjangoFilterBackend,)
filter_fields = ('title',)
filterset_fields = ('title',)
...
+4 -4
View File
@@ -229,7 +229,7 @@ Persist swagger-ui authorization data to local storage. |br|
**WARNING:** This may be a security risk as the credentials are stored unencrypted and can be accessed
by all javascript code running on the same domain.
**Default**: :python:`'False` |br|
**Default**: :python:`False` |br|
*Maps to parameter*: -
REFETCH_SCHEMA_WITH_AUTH
@@ -237,7 +237,7 @@ REFETCH_SCHEMA_WITH_AUTH
Re-fetch the OpenAPI document with the new credentials after authorization is performed through swagger-ui.
**Default**: :python:`'False` |br|
**Default**: :python:`False` |br|
*Maps to parameter*: -
REFETCH_SCHEMA_ON_LOGOUT
@@ -245,7 +245,7 @@ REFETCH_SCHEMA_ON_LOGOUT
Re-fetch the OpenAPI document without credentials after authorization is removed through swagger-ui.
**Default**: :python:`'False` |br|
**Default**: :python:`False` |br|
*Maps to parameter*: -
FETCH_SCHEMA_WITH_QUERY
@@ -253,7 +253,7 @@ FETCH_SCHEMA_WITH_QUERY
Fetch the OpenAPI document using the query parameters passed to the swagger-ui page request.
**Default**: :python:`'True` |br|
**Default**: :python:`True` |br|
*Maps to parameter*: -
OPERATIONS_SORTER
+57 -57
View File
@@ -4,9 +4,9 @@
"lockfileVersion": 1,
"dependencies": {
"@babel/runtime": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.1.2.tgz",
"integrity": "sha512-Y3SCjmhSupzFB6wcv1KmmFucH6gDVnI30WjOcicV10ju0cZjak3Jcs67YLIXBrmZYw1xCrVeJPbycFwrqNyxpg==",
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.1.5.tgz",
"integrity": "sha512-xKnPpXG/pvK1B90JkwwxSGii90rQGKtzcMt2gI5G6+M0REXaq6rOHsGC2ay6/d0Uje7zzvSzjEzfR3ENhFlrfA==",
"requires": {
"regenerator-runtime": "^0.12.0"
}
@@ -30,9 +30,9 @@
"integrity": "sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q=="
},
"clipboard": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.1.tgz",
"integrity": "sha512-7yhQBmtN+uYZmfRjjVjKa0dZdWuabzpSKGtyQZN+9C8xlC788SSJjOHWh7tzurfwTqTD5UDYAhIv5fRJg3sHjQ==",
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.4.tgz",
"integrity": "sha512-Vw26VSLRpJfBofiVaFb/I8PVfdI1OxKcYShe6fm0sP/DtmiWQNCjhM/okTvdCo0G+lMMm1rMYbk4IK4x1X+kgQ==",
"optional": true,
"requires": {
"good-listener": "^1.2.2",
@@ -40,14 +40,6 @@
"tiny-emitter": "^2.0.0"
}
},
"debug": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
"integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
"requires": {
"ms": "^2.1.1"
}
},
"decko": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decko/-/decko-1.2.0.tgz",
@@ -113,9 +105,12 @@
}
},
"hoist-non-react-statics": {
"version": "2.5.5",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz",
"integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw=="
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.2.0.tgz",
"integrity": "sha512-3IascCRfaEkbmHjJnUxWSspIUE1okLPjGTMVXW8zraUo1t3yg1BadKAxAGILHwgoBzmMnzrgeeaDGBvpuPz6dA==",
"requires": {
"react-is": "^16.3.2"
}
},
"js-tokens": {
"version": "4.0.0",
@@ -140,14 +135,13 @@
}
},
"json-schema-ref-parser": {
"version": "5.1.3",
"resolved": "https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-5.1.3.tgz",
"integrity": "sha512-CpDFlBwz/6la78hZxyB9FECVKGYjIIl3Ms3KLqFj99W7IIb7D00/RDgc++IGB4BBALl0QRhh5m4q5WNSopvLtQ==",
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/json-schema-ref-parser/-/json-schema-ref-parser-6.0.2.tgz",
"integrity": "sha512-EENU7mrmuBAdjSsAEJD8mMvodZyDhLBEfuSUBSIMuXqjs+cfMbFaxS8f6+ky675jetRzGzCdhzAU3y2VEtquvQ==",
"requires": {
"call-me-maybe": "^1.0.1",
"debug": "^3.1.0",
"js-yaml": "^3.12.0",
"ono": "^4.0.6"
"ono": "^4.0.10"
}
},
"loose-envify": {
@@ -159,9 +153,9 @@
}
},
"lunr": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.3.tgz",
"integrity": "sha512-rlAEsgU9Bnavca2w1WJ6+6cdeHMXNyadcersyk3ZpuhgWb5HBNj8l4WwJz9PjksAhYDlpQffCVXPctOn+wCIVA=="
"version": "2.3.5",
"resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.5.tgz",
"integrity": "sha512-EtnfmHsHJTr3u24sito9JctSxej5Ds0SgUD2Lm+qRHyLgM7BGesFlW14eNh1mil0fV5Muh8gf3dBBXzADlUlzQ=="
},
"mark.js": {
"version": "8.11.1",
@@ -169,14 +163,13 @@
"integrity": "sha1-GA8fnr74sOY45BZq1S24eb6y/8U="
},
"marked": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/marked/-/marked-0.5.1.tgz",
"integrity": "sha512-iUkBZegCZou4AdwbKTwSW/lNDcz5OuRSl3qdcl31Ia0B2QPG0Jn+tKblh/9/eP9/6+4h27vpoh8wel/vQOV0vw=="
"version": "git+https://github.com/markedjs/marked.git#fb48827236ed3a43e611d2adb3c070ca3f55ed8e",
"from": "git+https://github.com/markedjs/marked.git#fb48827"
},
"memoize-one": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-4.0.2.tgz",
"integrity": "sha512-ucx2DmXTeZTsS4GPPUZCbULAN7kdPT1G+H49Y34JjbQ5ESc6OGhVxKvb1iKhr9v19ZB9OtnHwNnhUnNR/7Wteg=="
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-4.0.3.tgz",
"integrity": "sha512-QmpUu4KqDmX0plH4u+tf0riMc1KHE1+lw95cMrLlXQAFOx/xnBtwhZ52XJxd9X2O6kwKBqX32kmhbhlobD0cuw=="
},
"min-document": {
"version": "2.19.0",
@@ -187,19 +180,14 @@
}
},
"mobx-react": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/mobx-react/-/mobx-react-5.2.8.tgz",
"integrity": "sha512-VAkeqkrIpdoy3VPPoqvxjdQmcTT6hi7i3TsZSwcKbSrPbSTuWc7cp1EOiX/zV1wPWEuoNAQ22bCrskQwvdYTJA==",
"version": "5.4.2",
"resolved": "https://registry.npmjs.org/mobx-react/-/mobx-react-5.4.2.tgz",
"integrity": "sha512-alSN0KDAAOb1OkYujfoJjjk0JWxWRKO4sLGB4hN2CuvaJMrlj7bhGQe7CBMJvEFNjtJRbhJcquYVjQ3rrH2zQQ==",
"requires": {
"hoist-non-react-statics": "^2.5.0",
"hoist-non-react-statics": "^3.0.0",
"react-lifecycles-compat": "^3.0.2"
}
},
"ms": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
},
"object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -227,9 +215,9 @@
"integrity": "sha512-/2Sk/khljhdrsamjJYS5NjrH+GKEHEwh7zFSiYyxROyYKagkE4kSn2zDQDRTOMo8mpT2jikxx6yI1dG7lNP/hw=="
},
"polished": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/polished/-/polished-2.2.0.tgz",
"integrity": "sha512-GEKeNET1XIri53xKpFwGZX4fh2k3b5GE5fxwLWYYR2sGWkMAHJVcb7bK1g6QHIDcoIEEGC8CzHOQgl2qFByd3w==",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/polished/-/polished-2.3.0.tgz",
"integrity": "sha512-G2yD9LhJy5HBuU+Im5qe70ubaJI/ZTTOIJO6GRMwJ2WSoAiPzlm8+LjAXMnm9/K0E0NumRVHvQu2HHPKQSYQjw==",
"requires": {
"@babel/runtime": "^7.0.0"
}
@@ -265,9 +253,9 @@
}
},
"react-hot-loader": {
"version": "4.3.11",
"resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.3.11.tgz",
"integrity": "sha512-T0G5jURyTsFLoiW6MTr5Q35UHC/B2pmYJ7+VBjk8yMDCEABRmCGy4g6QwxoB4pWg4/xYvVTa/Pbqnsgx/+NLuA==",
"version": "4.3.12",
"resolved": "https://registry.npmjs.org/react-hot-loader/-/react-hot-loader-4.3.12.tgz",
"integrity": "sha512-GMM4TsqUVss2QPe+Y33NlgydA5/+7tAVQxR0rZqWvBpapM8JhD7p6ymMwSZzr5yxjoXXlK/6P6qNQBOqm1dqdg==",
"requires": {
"fast-levenshtein": "^2.0.6",
"global": "^4.3.0",
@@ -275,8 +263,20 @@
"prop-types": "^15.6.1",
"react-lifecycles-compat": "^3.0.4",
"shallowequal": "^1.0.2"
},
"dependencies": {
"hoist-non-react-statics": {
"version": "2.5.5",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz",
"integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw=="
}
}
},
"react-is": {
"version": "16.6.3",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.6.3.tgz",
"integrity": "sha512-u7FDWtthB4rWibG/+mFbVd5FvdI20yde86qKGx4lVUTWmPlSWQ4QxbBIrrs+HnXGbxOUlUzTAP/VDmvCwaP2yA=="
},
"react-lifecycles-compat": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz",
@@ -292,19 +292,19 @@
}
},
"redoc": {
"version": "2.0.0-alpha.40",
"resolved": "https://registry.npmjs.org/redoc/-/redoc-2.0.0-alpha.40.tgz",
"integrity": "sha512-qc6wmw97a1Yh7LAqlF3BEVp8ualHaGjGLnsRL2O8BScqVmhFgyeAkFqayHdaT7qe5/g5Bge090U6Eq5OyvXi2Q==",
"version": "2.0.0-alpha.41",
"resolved": "https://registry.npmjs.org/redoc/-/redoc-2.0.0-alpha.41.tgz",
"integrity": "sha512-g8XnoDRRNLq2GVk8cNYKtO6cK5cPK95qdCIc6PSNo2ueBVWEQBKooriSF57B6GVuaqoOBacqlGHQDPakvBQLYA==",
"requires": {
"classnames": "^2.2.6",
"decko": "^1.2.0",
"dompurify": "^1.0.7",
"eventemitter3": "^3.0.0",
"json-pointer": "^0.6.0",
"json-schema-ref-parser": "^5.1.2",
"json-schema-ref-parser": "^6.0.1",
"lunr": "^2.3.2",
"mark.js": "^8.11.1",
"marked": "^0.5.1",
"marked": "git+https://github.com/markedjs/marked.git#fb48827236ed3a43e611d2adb3c070ca3f55ed8e",
"memoize-one": "^4.0.0",
"mobx-react": "^5.2.5",
"openapi-sampler": "1.0.0-beta.14",
@@ -337,9 +337,9 @@
"integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ=="
},
"slugify": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.3.1.tgz",
"integrity": "sha512-6BwyhjF5tG5P8s+0DPNyJmBSBePG6iMyhjvIW5zGdA3tFik9PtK+yNkZgTeiroCRGZYgkHftFA62tGVK1EI9Kw=="
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.3.3.tgz",
"integrity": "sha512-aFvcXobuowA7RqU4IBVJvqmhkREDIqsj4oIJKk6JuZ5EO1PCwtAAwDCl8TdsMs4J9zCoDAVkB9FLUElDjNcRSg=="
},
"sprintf-js": {
"version": "1.0.3",
@@ -352,9 +352,9 @@
"integrity": "sha1-OUE/7p0CXHSn5ZzuyyN4TMDxfwI="
},
"swagger-ui-dist": {
"version": "3.19.3",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.19.3.tgz",
"integrity": "sha512-bHH4yJrOpNCxLPqoEx2ZdwSuLMmc+V3JmFM9oetqWKKRv9AgUnrO1XNhePe9uc53QPaeJ0nCf3cLCxJBle6hjA=="
"version": "3.20.4",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.20.4.tgz",
"integrity": "sha512-SR/N+N7EIncEhyA4UGiMQ12vJBSv5OKO4S1g7E7etO+9ZUV6SZ7SqKVC8RDDyMOJzdXgMXV7aGIBIiMSCbEMJw=="
},
"tiny-emitter": {
"version": "2.0.2",
+2 -2
View File
@@ -1,8 +1,8 @@
{
"name": "drf-yasg",
"dependencies": {
"redoc": "^2.0.0-alpha.40",
"swagger-ui-dist": "^3.19.3"
"redoc": "^2.0.0-alpha.41",
"swagger-ui-dist": "^3.20.4"
},
"repository": {
"type": "git",
+3
View File
@@ -0,0 +1,3 @@
[build-system]
requires = ["setuptools >= 40.6.3", "wheel", "setuptools-scm >= 3.0.3"]
build-backend = "setuptools.build_meta"
+2 -1
View File
@@ -1,3 +1,4 @@
-r requirements/setup.txt
# this file is only used when deploying to heroku, because heroku insists on having a root-level requirements.txt
# for normal usage see the requirements/ directory
.[validation]
-r requirements/heroku.txt
+2 -1
View File
@@ -2,7 +2,8 @@
Sphinx>=1.7.0
sphinx_rtd_theme>=0.2.4
Pillow>=4.3.0
readme_renderer>=17.2
readme_renderer[md]>=24.0
twine>=1.12.1
Django>=2.0
djangorestframework_camel_case>=0.2.0
-3
View File
@@ -1,3 +0,0 @@
# needed to build the package setup_requires in setup.py
setuptools-scm>=3.0.6
+4 -4
View File
@@ -1,9 +1,9 @@
# requirements for running the tests via pytest
pytest>=2.9,<3.7 # <3.7 because of incompatible pluggy requirement
pytest>=4.0
pytest-pythonpath>=0.7.1
pytest-cov>=2.5.1
pytest-xdist>=1.22.0
pytest-django>=3.2.0
pytest-cov>=2.6.0
pytest-xdist>=1.25.0
pytest-django>=3.4.4
datadiff==2.0.0
-r testproj.txt
+2
View File
@@ -8,3 +8,5 @@ djangorestframework-camel-case>=0.2.0
djangorestframework-recursive>=0.1.2
dj-database-url>=0.4.2
user_agents>=1.1.0
# django-oauth-toolkit 1.2 does not support Django 1.11
django-oauth-toolkit>=1.1.0,<1.2.0
+1 -3
View File
@@ -1,4 +1,2 @@
# requirements for building and running tox
tox>=3.1.2
-r setup.txt
tox>=3.3.0
+1 -1
View File
@@ -1 +1 @@
python-3.6.6
python-3.7.1
+11 -7
View File
@@ -17,7 +17,6 @@ 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')
@@ -28,7 +27,6 @@ def drf_yasg_setup(**kwargs):
package_dir={'': 'src'},
include_package_data=True,
install_requires=requirements,
setup_requires=requirements_setup,
extras_require={
'validation': requirements_validation,
},
@@ -67,21 +65,27 @@ def drf_yasg_setup(**kwargs):
try:
# noinspection PyUnresolvedReferences
import setuptools_scm # noqa: F401
drf_yasg_setup(use_scm_version=True)
except LookupError as e:
except (ImportError, LookupError) as e:
if os.getenv('CI', 'false') == 'true' or os.getenv('TRAVIS', 'false') == 'true':
# don't silently fail on travis - we don't want to accidentally push a dummy version to PyPI
raise
if 'setuptools-scm' in str(e):
err_msg = str(e)
if 'setuptools-scm' in err_msg or 'setuptools_scm' in err_msg:
import time
import traceback
timestamp_ms = int(time.time() * 1000)
timestamp_str = hex(timestamp_ms)[2:].zfill(16)
dummy_version = '0.0.0rc0+noscm' + timestamp_str
dummy_version = '1!0.0.0.dev0+noscm.' + timestamp_str
drf_yasg_setup(version=dummy_version)
print(str(e), file=sys.stderr)
print("failed to detect version, build was done using dummy version " + dummy_version, file=sys.stderr)
traceback.print_exc(file=sys.stderr)
print("failed to detect version, package was built with dummy version " + dummy_version, file=sys.stderr)
else:
raise
+15 -10
View File
@@ -2,6 +2,7 @@ from six import raise_from
import copy
import json
import logging
from collections import OrderedDict
from coreapi.compat import force_bytes
@@ -10,6 +11,8 @@ from ruamel import yaml
from . import openapi
from .errors import SwaggerValidationError
logger = logging.getLogger(__name__)
def _validate_flex(spec):
from flex.core import parse as validate_flex
@@ -70,7 +73,10 @@ class _OpenAPICodec(object):
errors[validator] = str(e)
if errors:
raise SwaggerValidationError("spec validation failed", errors, spec, self)
exc = SwaggerValidationError("spec validation failed: {}".format(errors), errors, spec, self)
logger.warning(str(exc))
raise exc
return force_bytes(self._dump_dict(spec))
def encode_error(self, err):
@@ -121,8 +127,7 @@ class SaneYamlDumper(yaml.SafeDumper):
"""
return super(SaneYamlDumper, self).increase_indent(flow=flow, indentless=False, **kwargs)
@staticmethod
def represent_odict(dump, mapping, flow_style=None): # pragma: no cover
def represent_odict(self, mapping, flow_style=None): # pragma: no cover
"""https://gist.github.com/miracle2k/3184458
Make PyYAML output an OrderedDict.
@@ -134,22 +139,22 @@ class SaneYamlDumper(yaml.SafeDumper):
tag = YAML_MAP_TAG
value = []
node = yaml.MappingNode(tag, value, flow_style=flow_style)
if dump.alias_key is not None:
dump.represented_objects[dump.alias_key] = node
if self.alias_key is not None:
self.represented_objects[self.alias_key] = node
best_style = True
if hasattr(mapping, 'items'):
mapping = mapping.items()
for item_key, item_value in mapping:
node_key = dump.represent_data(item_key)
node_value = dump.represent_data(item_value)
node_key = self.represent_data(item_key)
node_value = self.represent_data(item_value)
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
best_style = False
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
best_style = False
value.append((node_key, node_value))
if flow_style is None:
if dump.default_flow_style is not None:
node.flow_style = dump.default_flow_style
if self.default_flow_style is not None:
node.flow_style = self.default_flow_style
else:
node.flow_style = best_style
return node
@@ -170,7 +175,7 @@ def yaml_sane_dump(data, binary):
: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
:rtype: str or bytes
"""
return yaml.dump(data, Dumper=SaneYamlDumper, default_flow_style=False, encoding='utf-8' if binary else None)
+69 -25
View File
@@ -8,15 +8,15 @@ from coreapi.compat import urlparse
from rest_framework import versioning
from rest_framework.compat import URLPattern, URLResolver, get_original_route
from rest_framework.schemas.generators import EndpointEnumerator as _EndpointEnumerator
from rest_framework.schemas.generators import SchemaGenerator, endpoint_ordering
from rest_framework.schemas.generators import SchemaGenerator, endpoint_ordering, get_pk_name
from rest_framework.schemas.inspectors import get_pk_description
from rest_framework.settings import api_settings as rest_framework_settings
from rest_framework.settings import api_settings
from . import openapi
from .app_settings import swagger_settings
from .errors import SwaggerGenerationError
from .inspectors.field import get_basic_type_info, get_queryset_field, get_queryset_from_view
from .openapi import ReferenceResolver
from .openapi import ReferenceResolver, SwaggerDict
from .utils import force_real_str, get_consumes, get_produces
logger = logging.getLogger(__name__)
@@ -132,7 +132,7 @@ class EndpointEnumerator(_EndpointEnumerator):
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
``simplify_regex`` does not handle this correctly.
**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
@@ -164,7 +164,7 @@ class OpenAPISchemaGenerator(object):
def __init__(self, info, version='', url=None, patterns=None, urlconf=None):
"""
:param .Info info: information about the API
:param openapi.Info info: information about the 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
@@ -198,11 +198,40 @@ class OpenAPISchemaGenerator(object):
def url(self):
return self._gen.url
def get_security_definitions(self):
"""Get the security schemes for this API. This determines what is usable in security requirements,
and helps clients configure their authorization credentials.
:return: the security schemes usable with this API
:rtype: dict[str,dict] or None
"""
security_definitions = swagger_settings.SECURITY_DEFINITIONS
if security_definitions is not None:
security_definitions = SwaggerDict._as_odict(security_definitions, {})
return security_definitions
def get_security_requirements(self, security_definitions):
"""Get the base (global) security requirements of the API. This is never called if
:meth:`.get_security_definitions` returns `None`.
:param security_definitions: security definitions as returned by :meth:`.get_security_definitions`
:return: the security schemes accepted by default
:rtype: list[dict[str,list[str]]] or None
"""
security_requirements = swagger_settings.SECURITY_REQUIREMENTS
if security_requirements is None:
security_requirements = [{security_scheme: []} for security_scheme in security_definitions]
security_requirements = [SwaggerDict._as_odict(sr, {}) for sr in security_requirements]
security_requirements = sorted(security_requirements, key=list)
return security_requirements
def get_schema(self, request=None, public=False):
"""Generate a :class:`.Swagger` object representing the API schema.
:param Request request: the request used for filtering
accesible endpoints and finding the spec URI
:param request: the request used for filtering accesible endpoints and finding the spec URI
:type request: rest_framework.request.Request or None
:param bool public: if True, all endpoints are included regardless of access through `request`
:return: the generated Swagger specification
@@ -210,20 +239,15 @@ class OpenAPISchemaGenerator(object):
"""
endpoints = self.get_endpoints(request)
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
self.consumes = get_consumes(rest_framework_settings.DEFAULT_PARSER_CLASSES)
self.produces = get_produces(rest_framework_settings.DEFAULT_RENDERER_CLASSES)
self.consumes = get_consumes(api_settings.DEFAULT_PARSER_CLASSES)
self.produces = get_produces(api_settings.DEFAULT_RENDERER_CLASSES)
paths, prefix = self.get_paths(endpoints, components, request, public)
security_definitions = swagger_settings.SECURITY_DEFINITIONS
if security_definitions is not None:
security_definitions = OrderedDict(sorted([(key, OrderedDict(sorted(sd.items())))
for key, sd in swagger_settings.SECURITY_DEFINITIONS.items()]))
security_requirements = swagger_settings.SECURITY_REQUIREMENTS
if security_requirements is None:
security_requirements = [{security_scheme: []} for security_scheme in swagger_settings.SECURITY_DEFINITIONS]
security_requirements = sorted(security_requirements, key=lambda od: list(sorted(od)))
security_requirements = [OrderedDict(sorted(sr.items())) for sr in security_requirements]
security_definitions = self.get_security_definitions()
if security_definitions:
security_requirements = self.get_security_requirements(security_definitions)
else:
security_requirements = None
url = self.url
if url is None and request is not None:
@@ -238,9 +262,10 @@ class OpenAPISchemaGenerator(object):
def create_view(self, callback, method, request=None):
"""Create a view instance from a view callback as registered in urlpatterns.
:param callable callback: view callback registered in urlpatterns
:param callback: view callback registered in urlpatterns
:param str method: HTTP method
:param rest_framework.request.Request request: request to bind to the view
:param request: request to bind to the view
:type request: rest_framework.request.Request or None
:return: the view instance
"""
view = self._gen.create_view(callback, method, request)
@@ -255,12 +280,31 @@ class OpenAPISchemaGenerator(object):
setattr(view, 'swagger_fake_view', True)
return view
def coerce_path(self, path, view):
"""Coerce {pk} path arguments into the name of the model field, where possible. This is cleaner for an
external representation (i.e. "this is an identifier", not "this is a database primary key").
:param str path: the path
:param rest_framework.views.APIView view: associated view
:rtype: str
"""
if '{pk}' not in path:
return path
model = getattr(get_queryset_from_view(view), 'model', None)
if model:
field_name = get_pk_name(model)
else:
field_name = 'id'
return path.replace('{pk}', '{%s}' % field_name)
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: request to bind to the endpoint views
:param request: request to bind to the endpoint views
:type request: rest_framework.request.Request or None
:return: {path: (view_class, list[(http_method, view_instance)])
:rtype: dict
:rtype: dict[str,(type,list[(str,rest_framework.views.APIView)])]
"""
enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf, request=request)
endpoints = enumerator.get_api_endpoints()
@@ -269,7 +313,7 @@ class OpenAPISchemaGenerator(object):
view_cls = {}
for path, method, callback in endpoints:
view = self.create_view(callback, method, request)
path = self._gen.coerce_path(path, method, view)
path = self.coerce_path(path, view)
view_paths[path].append((method, view))
view_cls[path] = callback.cls
return {path: (view_cls[path], methods) for path, methods in view_paths.items()}
@@ -287,7 +331,7 @@ class OpenAPISchemaGenerator(object):
:param str subpath: path to the operation with any common prefix/base path removed
:param str method: HTTP method
:param view: the view associated with the operation
:rtype: tuple
:rtype: list[str]
"""
return self._gen.get_keys(subpath, method, view)
+51 -10
View File
@@ -4,7 +4,7 @@ import logging
from rest_framework import serializers
from .. import openapi
from ..utils import force_real_str, get_field_default, is_list_view
from ..utils import force_real_str, get_field_default, get_object_classes, is_list_view
#: Sentinel value that inspectors must return to signal that they do not know how to handle an object
NotHandled = object()
@@ -12,14 +12,38 @@ NotHandled = object()
logger = logging.getLogger(__name__)
def call_view_method(view, method_name, fallback_attr=None, default=None):
"""Call a view method which might throw an exception. If an exception is thrown, log an informative error message
and return the value of fallback_attr, or default if not present.
:param rest_framework.views.APIView view:
:param str method_name: name of a method on the view
:param str fallback_attr: name of an attribute on the view to fall back on, if calling the method fails
:param default: default value if all else fails
:return: view method's return value, or value of view's fallback_attr, or default
"""
if hasattr(view, method_name):
try:
return getattr(view, method_name)()
except Exception: # pragma: no cover
logger.warning("view's %s.get_parsers raised exception during schema generation; use "
"`getattr(self, 'swagger_fake_view', False)` to detect and short-circuit this",
type(view).__name__, exc_info=True)
if fallback_attr and hasattr(view, fallback_attr):
return getattr(view, fallback_attr)
return default
class BaseInspector(object):
def __init__(self, view, path, method, components, request):
"""
:param view: the view associated with this endpoint
:param rest_framework.views.APIView 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
:param rest_framework.request.Request request: the request made against the schema view; can be None
"""
self.view = view
self.path = path
@@ -81,6 +105,22 @@ class BaseInspector(object):
return result
def get_renderer_classes(self):
"""Get the renderer classes of this view by calling `get_renderers`.
:return: renderer classes
:rtype: list[type[rest_framework.renderers.BaseRenderer]]
"""
return get_object_classes(call_view_method(self.view, 'get_renderers', 'renderer_classes', []))
def get_parser_classes(self):
"""Get the parser classes of this view by calling `get_parsers`.
:return: parser classes
:rtype: list[type[rest_framework.parsers.BaseParser]]
"""
return get_object_classes(call_view_method(self.view, 'get_parsers', 'parser_classes', []))
class PaginatorInspector(BaseInspector):
"""Base inspector for paginators.
@@ -159,7 +199,7 @@ class FieldInspector(BaseInspector):
: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
:rtype: openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef
"""
return NotHandled
@@ -168,7 +208,7 @@ class FieldInspector(BaseInspector):
All arguments are the same as :meth:`.field_to_swagger_object`.
:rtype: openapi.Parameter,openapi.Items,openapi.Schema,openapi.SchemaRef
:rtype: openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef
"""
return self.probe_inspectors(
self.field_inspectors, 'field_to_swagger_object', field, {'field_inspectors': self.field_inspectors},
@@ -203,7 +243,7 @@ class FieldInspector(BaseInspector):
- :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])]
:rtype: (function,type[openapi.Schema] or 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"
@@ -335,7 +375,7 @@ class ViewInspector(BaseInspector):
return []
fields = []
for filter_backend in self.view.filter_backends:
for filter_backend in getattr(self.view, 'filter_backends'):
fields += self.probe_inspectors(self.filter_inspectors, 'get_filter_parameters', filter_backend()) or []
return fields
@@ -361,14 +401,15 @@ class ViewInspector(BaseInspector):
if not self.should_page():
return []
return self.probe_inspectors(self.paginator_inspectors, 'get_paginator_parameters', self.view.paginator) or []
return self.probe_inspectors(self.paginator_inspectors, 'get_paginator_parameters',
getattr(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
:rtype: openapi.Schema or openapi.SchemaRef
"""
return self.probe_inspectors(
self.field_inspectors, 'get_schema', serializer, {'field_inspectors': self.field_inspectors}
@@ -394,4 +435,4 @@ class ViewInspector(BaseInspector):
:rtype: openapi.Schema
"""
return self.probe_inspectors(self.paginator_inspectors, 'get_paginated_response',
self.view.paginator, response_schema=response_schema)
getattr(self.view, 'paginator'), response_schema=response_schema)
+24 -12
View File
@@ -14,7 +14,7 @@ from rest_framework.settings import api_settings as rest_framework_settings
from .. import openapi
from ..errors import SwaggerGenerationError
from ..utils import decimal_as_float, filter_none, get_serializer_class, get_serializer_ref_name
from .base import FieldInspector, NotHandled, SerializerInspector
from .base import FieldInspector, NotHandled, SerializerInspector, call_view_method
try:
import typing
@@ -58,6 +58,7 @@ class InlineSerializerInspector(SerializerInspector):
)
for key, value
in fields.items()
if not getattr(value, 'read_only', False)
]
return self.add_manual_parameters(serializer, parameters)
@@ -176,7 +177,7 @@ def get_queryset_from_view(view, serializer=None):
:return: queryset or ``None``
"""
try:
queryset = getattr(view, 'queryset', None)
queryset = call_view_method(view, 'get_queryset', 'queryset', None)
if queryset is not None and serializer is not None:
# make sure the view is actually using *this* serializer
@@ -322,8 +323,8 @@ limit_validators = [
(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__),
(validators.MinLengthValidator, (serializers.ListField, serializers.ListSerializer), 'min_items', operator.__gt__),
(validators.MaxLengthValidator, (serializers.ListField, serializers.ListSerializer), 'max_items', operator.__lt__),
]
@@ -513,12 +514,10 @@ class SerializerMethodFieldInspector(FieldInspector):
if method is None:
return NotHandled
# attribute added by the swagger_serializer_method decorator
serializer = getattr(method, "_swagger_serializer", None)
if serializer:
# attribute added by the swagger_serializer_method decorator
serializer = getattr(method, '_swagger_serializer', None)
# in order of preference for description, use:
# 1) field.help_text from SerializerMethodField(help_text)
# 2) serializer.help_text from swagger_serializer_method(serializer)
@@ -586,6 +585,7 @@ class ChoiceFieldInspector(FieldInspector):
if isinstance(field, serializers.ChoiceField):
enum_type = openapi.TYPE_STRING
enum_values = list(field.choices.keys())
# for ModelSerializer, try to infer the type from the associated model field
serializer = get_parent_serializer(field)
@@ -596,17 +596,29 @@ class ChoiceFieldInspector(FieldInspector):
model_type = get_basic_type_info(model_field)
if model_type:
enum_type = model_type.get('type', enum_type)
else:
# Try to infer field type based on enum values
enum_value_types = {type(v) for v in enum_values}
if len(enum_value_types) == 1:
values_type = get_basic_type_info_from_hint(next(iter(enum_value_types)))
if values_type:
enum_type = values_type.get('type', enum_type)
if isinstance(field, serializers.MultipleChoiceField):
return SwaggerType(
result = SwaggerType(
type=openapi.TYPE_ARRAY,
items=ChildSwaggerType(
type=enum_type,
enum=list(field.choices.keys())
enum=enum_values
)
)
if swagger_object_type == openapi.Parameter:
if result['in'] in (openapi.IN_FORM, openapi.IN_QUERY):
result.collection_format = 'multi'
else:
result = SwaggerType(type=enum_type, enum=enum_values)
return SwaggerType(type=enum_type, enum=list(field.choices.keys()))
return result
return NotHandled
@@ -721,8 +733,8 @@ class CamelCaseJSONFilter(FieldInspector):
if CamelCaseJSONParser and CamelCaseJSONRenderer:
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)
any(issubclass(parser, CamelCaseJSONParser) for parser in self.get_parser_classes()) or
any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.get_renderer_classes())
)
else:
def is_camel_case(self):
+8 -4
View File
@@ -44,12 +44,16 @@ class CoreAPICompatInspector(PaginatorInspector, FilterInspector):
coreschema.String: openapi.TYPE_STRING,
coreschema.Boolean: openapi.TYPE_BOOLEAN,
}
coreschema_attrs = ['format', 'pattern', 'enum', 'min_length', 'max_length']
schema = field.schema
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=force_real_str(field.schema.description) if field.schema else None,
description=force_real_str(schema.description) if schema else None,
type=coreapi_types.get(type(schema), openapi.TYPE_STRING),
**OrderedDict((attr, getattr(schema, attr, None)) for attr in coreschema_attrs)
)
@@ -67,8 +71,8 @@ class DjangoRestResponsePagination(PaginatorInspector):
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)),
('next', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI, x_nullable=True)),
('previous', openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI, x_nullable=True)),
('results', response_schema),
)),
required=['results']
+78 -45
View File
@@ -1,4 +1,5 @@
import logging
import warnings
from collections import OrderedDict
from rest_framework.request import is_form_media_type
@@ -8,12 +9,12 @@ from rest_framework.status import is_success
from .. import openapi
from ..errors import SwaggerGenerationError
from ..utils import (
force_real_str, force_serializer_instance, get_consumes, get_produces, guess_response_status, is_list_view,
merge_params, no_body, param_list_to_odict
filter_none, force_real_str, force_serializer_instance, get_consumes, get_produces, guess_response_status,
is_list_view, merge_params, no_body, param_list_to_odict
)
from .base import ViewInspector
from .base import ViewInspector, call_view_method
log = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
class SwaggerAutoSchema(ViewInspector):
@@ -22,6 +23,22 @@ class SwaggerAutoSchema(ViewInspector):
self._sch = AutoSchema()
self._sch.view = view
def _summary_and_description_compat(self):
# TODO: remove in 1.13
base_methods = (SwaggerAutoSchema.get_summary, SwaggerAutoSchema.get_description)
self_methods = (type(self).get_summary, type(self).get_description)
if self_methods != base_methods:
warnings.warn(
"`SwaggerAutoSchema` methods `get_summary` and `get_description` are deprecated and "
"will be removed in drf-yasg 1.13. Override `get_summary_and_description` instead.",
DeprecationWarning, stacklevel=2
)
# if get_summary or get_description are overriden by a child class,
# we must call them for backwards compatibility
return self.get_summary(), self.get_description()
return self.get_summary_and_description()
def get_operation(self, operation_keys):
consumes = self.get_consumes()
produces = self.get_produces()
@@ -29,14 +46,13 @@ class SwaggerAutoSchema(ViewInspector):
body = self.get_request_body_parameters(consumes)
query = self.get_query_parameters()
parameters = body + query
parameters = [param for param in parameters if param is not None]
parameters = filter_none(parameters)
parameters = self.add_manual_parameters(parameters)
operation_id = self.get_operation_id(operation_keys)
description = self.get_description()
summary = self.get_summary()
summary, description = self._summary_and_description_compat()
security = self.get_security()
assert security is None or isinstance(security, list), "security must be a list of securiy requirement objects"
assert security is None or isinstance(security, list), "security must be a list of security requirement objects"
deprecated = self.is_deprecated()
tags = self.get_tags(operation_keys)
@@ -87,21 +103,12 @@ class SwaggerAutoSchema(ViewInspector):
"""Return the serializer as defined by the view's ``get_serializer()`` method.
:return: the view's ``Serializer``
:rtype: rest_framework.serializers.Serializer
"""
if not hasattr(self.view, 'get_serializer'):
return None
try:
return self.view.get_serializer()
except Exception:
log.warning("view's get_serializer raised exception (%s %s %s)",
self.method, self.path, type(self.view).__name__, exc_info=True)
return None
return call_view_method(self.view, 'get_serializer')
def _get_request_body_override(self):
"""Parse the request_body key in the override dict. This method is not public API.
:return:
"""
"""Parse the request_body key in the override dict. This method is not public API."""
body_override = self.overrides.get('request_body', None)
if body_override is not None:
@@ -120,6 +127,7 @@ class SwaggerAutoSchema(ViewInspector):
"""Return the request serializer (used for parsing the request payload) for this endpoint.
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
:rtype: rest_framework.serializers.Serializer
"""
body_override = self._get_request_body_override()
@@ -167,12 +175,13 @@ class SwaggerAutoSchema(ViewInspector):
if any(param.in_ == openapi.IN_BODY for param in manual_parameters): # pragma: no cover
raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body")
if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover
if any(param.in_ == openapi.IN_BODY for param in parameters):
has_body_parameter = any(param.in_ == openapi.IN_BODY for param in parameters)
if has_body_parameter or not any(is_form_media_type(encoding) for encoding in self.get_consumes()):
raise SwaggerGenerationError("cannot add form parameters when the request has a request body; "
"did you forget to set an appropriate parser class on the view?")
if self.method not in self.body_methods:
raise SwaggerGenerationError("form parameters can only be applied to (" + ','.join(self.body_methods) +
") HTTP methods")
raise SwaggerGenerationError("form parameters can only be applied to "
"(" + ','.join(self.body_methods) + ") HTTP methods")
return merge_params(parameters, manual_parameters)
@@ -321,7 +330,32 @@ class SwaggerAutoSchema(ViewInspector):
operation_id = '_'.join(operation_keys)
return operation_id
def _extract_description_and_summary(self):
def split_summary_from_description(self, description):
"""Decide if and how to split a summary out of the given description. The default implementation
uses the first paragraph of the description as a summary if it is less than 120 characters long.
:param description: the full description to be analyzed
:return: summary and description
:rtype: (str,str)
"""
# https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings
summary = None
summary_max_len = 120 # OpenAPI 2.0 spec says summary should be under 120 characters
sections = description.split('\n\n', 1)
if len(sections) == 2:
sections[0] = sections[0].strip()
if len(sections[0]) < summary_max_len:
summary, description = sections
description = description.strip()
return summary, description
def get_summary_and_description(self):
"""Return an operation summary and description determined from the view's docstring.
:return: summary and description
:rtype: (str,str)
"""
description = self.overrides.get('operation_description', None)
summary = self.overrides.get('operation_summary', None)
if description is None:
@@ -330,23 +364,9 @@ class SwaggerAutoSchema(ViewInspector):
if description and (summary is None):
# description from docstring ... do summary magic
# https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings
summary_max_len = 120 # OpenAPI 2.0 spec says summary should be under 120 characters
sections = description.split('\n\n', 1)
if len(sections) == 2:
sections[0] = sections[0].strip()
if len(sections[0]) < summary_max_len:
summary, description = sections
summary, description = self.split_summary_from_description(description)
return description, summary
def get_description(self):
"""Return an operation description determined as appropriate from the view's method and class docstrings.
:return: the operation description
:rtype: str
"""
return self._extract_description_and_summary()[0]
return summary, description
def get_summary(self):
"""Return a summary description for this operation.
@@ -354,7 +374,15 @@ class SwaggerAutoSchema(ViewInspector):
:return: the summary
:rtype: str
"""
return self._extract_description_and_summary()[1]
return self.get_summary_and_description()[0]
def get_description(self):
"""Return an operation description determined as appropriate from the view's method and class docstrings.
:return: the operation description
:rtype: str
"""
return self.get_summary_and_description()[1]
def get_security(self):
"""Return a list of security requirements for this operation.
@@ -376,24 +404,29 @@ class SwaggerAutoSchema(ViewInspector):
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.
each tag will show as a group containing the operations that use it. If not provided in overrides,
tags will be inferred from the operation url.
: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]]
tags = self.overrides.get('tags')
if not tags:
tags = [operation_keys[0]]
return tags
def get_consumes(self):
"""Return the MIME types this endpoint can consume.
:rtype: list[str]
"""
return get_consumes(getattr(self.view, 'parser_classes', []))
return get_consumes(self.get_parser_classes())
def get_produces(self):
"""Return the MIME types this endpoint can produce.
:rtype: list[str]
"""
return get_produces(getattr(self.view, 'renderer_classes', []))
return get_produces(self.get_renderer_classes())
@@ -43,7 +43,7 @@ class Command(BaseCommand):
)
parser.add_argument(
'-f', '--format', dest='format',
default='', choices=('json', 'yaml'),
default='', choices=['json', 'yaml'],
type=str,
help='Output format. If not given, it is guessed from the output file extension and defaults to json.'
)
@@ -158,6 +158,7 @@ class Command(BaseCommand):
else:
# normally this would be easily done with open(mode='x'/'w'),
# but python 2 is a pain in the ass as usual
# TODO: simplify when dropping support for python 2.7
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:
+72 -46
View File
@@ -1,12 +1,21 @@
import six
import collections
import logging
import re
from collections import OrderedDict
from coreapi.compat import urlparse
from django.urls import get_script_prefix
from django.utils.functional import Promise
from inflection import camelize
from .utils import filter_none
from .utils import filter_none, force_real_str
try:
from collections import abc as collections_abc
except ImportError:
collections_abc = collections
logger = logging.getLogger(__name__)
@@ -128,13 +137,22 @@ class SwaggerDict(OrderedDict):
if id(obj) in memo:
return memo[id(obj)]
if isinstance(obj, dict):
if isinstance(obj, Promise) and hasattr(obj, '_proxy____cast'):
# handle __proxy__ objects from django.utils.functional.lazy
obj = obj._proxy____cast()
if isinstance(obj, collections_abc.Mapping):
result = OrderedDict()
memo[id(obj)] = result
for attr, val in obj.items():
items = obj.items()
if not isinstance(obj, OrderedDict):
items = sorted(items)
for attr, val in items:
result[attr] = SwaggerDict._as_odict(val, memo)
return result
elif isinstance(obj, (list, tuple)):
elif isinstance(obj, six.string_types):
return force_real_str(obj)
elif isinstance(obj, collections_abc.Iterable) and not isinstance(obj, collections_abc.Iterator):
return type(obj)(SwaggerDict._as_odict(elem, memo) for elem in obj)
return obj
@@ -224,12 +242,12 @@ class Swagger(SwaggerDict):
:param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi
SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable
:param str _version: version string to override Info
:param dict[str,dict[str,str]] security_definitions: list of supported authentication mechanisms
:param list[dict] security: authentication mechanisms accepted by default; can be overriden in Operation
:param dict[str,dict] security_definitions: list of supported authentication mechanisms
:param list[dict[str,list[str]]] security: authentication mechanisms accepted globally
:param list[str] consumes: consumed MIME types; can be overriden in Operation
:param list[str] produces: produced MIME types; can be overriden in Operation
:param .Paths paths: paths object
:param dict[str,.Schema] definitions: named models
:param Paths paths: paths object
:param dict[str,Schema] definitions: named models
"""
super(Swagger, self).__init__(**extra)
self.swagger = '2.0'
@@ -280,7 +298,7 @@ class Paths(SwaggerDict):
def __init__(self, paths, **extra):
"""A listing of all the paths in the API.
:param dict[str,.PathItem] paths:
:param dict[str,PathItem] paths:
"""
super(Paths, self).__init__(**extra)
for path, path_obj in paths.items():
@@ -297,14 +315,14 @@ class PathItem(SwaggerDict):
head=None, patch=None, parameters=None, **extra):
"""Information about a single path
:param .Operation get: operation for GET
:param .Operation put: operation for PUT
:param .Operation post: operation for POST
:param .Operation delete: operation for DELETE
:param .Operation options: operation for OPTIONS
:param .Operation head: operation for HEAD
:param .Operation patch: operation for PATCH
:param list[.Parameter] parameters: parameters that apply to all operations
:param Operation get: operation for GET
:param Operation put: operation for PUT
:param Operation post: operation for POST
:param Operation delete: operation for DELETE
:param Operation options: operation for OPTIONS
:param Operation head: operation for HEAD
:param Operation patch: operation for PATCH
:param list[Parameter] parameters: parameters that apply to all operations
"""
super(PathItem, self).__init__(**extra)
self.get = get
@@ -333,8 +351,8 @@ class Operation(SwaggerDict):
"""Information about an API operation (path + http method combination)
:param str operation_id: operation ID, should be unique across all operations
:param .Responses responses: responses returned
:param list[.Parameter] parameters: parameters accepted
:param Responses responses: responses returned
:param list[Parameter] parameters: parameters accepted
:param list[str] consumes: content types accepted
:param list[str] produces: content types produced
:param str summary: operation summary; should be < 120 characters
@@ -355,6 +373,17 @@ class Operation(SwaggerDict):
self._insert_extras__()
def _check_type(type, format, enum, pattern, items, _obj_type):
if items and type != TYPE_ARRAY:
raise AssertionError("items can only be used when type is array")
if type == TYPE_ARRAY and not items:
raise AssertionError("TYPE_ARRAY requires the items attribute")
if pattern and type != TYPE_STRING:
raise AssertionError("pattern can only be used when type is string")
if (format or enum or pattern) and type in (TYPE_OBJECT, TYPE_ARRAY, None):
raise AssertionError("[format, enum, pattern] can only be applied to primitive " + _obj_type)
class Items(SwaggerDict):
def __init__(self, type=None, format=None, enum=None, pattern=None, items=None, **extra):
"""Used when defining an array :class:`.Parameter` to describe the array elements.
@@ -373,10 +402,7 @@ class Items(SwaggerDict):
self.pattern = pattern
self.items = items
self._insert_extras__()
if items and type != TYPE_ARRAY:
raise AssertionError("items can only be used when type is array")
if pattern and type != TYPE_STRING:
raise AssertionError("pattern can only be used when type is string")
_check_type(type, format, enum, pattern, items, self.__class__)
class Parameter(SwaggerDict):
@@ -389,7 +415,8 @@ class Parameter(SwaggerDict):
:param str in_: parameter location
:param str description: parameter description
:param bool required: whether the parameter is required for the operation
:param .Schema,.SchemaRef schema: required if `in_` is ``body``
:param schema: required if `in_` is ``body``
:type schema: Schema or SchemaRef
:param str type: parameter type; required if `in_` is not ``body``; must not be ``object``
:param str format: value format, see OpenAPI spec
:param list enum: restrict possible values
@@ -420,12 +447,9 @@ class Parameter(SwaggerDict):
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")
if default and not type:
raise AssertionError("default can only be applied to a non-body Parameter")
_check_type(type, format, enum, pattern, items, self.__class__)
class Schema(SwaggerDict):
@@ -441,10 +465,13 @@ class Schema(SwaggerDict):
:param str format: value format, see OpenAPI spec
:param list enum: restrict possible values
:param str pattern: pattern if type is ``string``
:param dict[str,(.Schema,.SchemaRef)] properties: object properties; required if `type` is ``object``
:param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties`
:param properties: object properties; required if `type` is ``object``
:type properties: dict[str,Schema or SchemaRef]
:param additional_properties: allow wildcard properties not listed in `properties`
:type additional_properties: bool or Schema or SchemaRef
:param list[str] required: list of requried property names
:param .Schema,.SchemaRef items: type of array items, only valid if `type` is ``array``
:param items: type of array items, only valid if `type` is ``array``
:type items: Schema or SchemaRef
: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``;
@@ -471,12 +498,7 @@ class Schema(SwaggerDict):
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")
_check_type(type, format, enum, pattern, items, self.__class__)
def _remove_read_only(self):
# readOnly is only valid for Schemas inside another Schema's properties;
@@ -495,7 +517,7 @@ class _Ref(SwaggerDict):
:param str name: referenced object name, e.g. "Article"
:param str scope: reference scope, e.g. "definitions"
:param type[.SwaggerDict] expected_type: the expected type that will be asserted on the object found in resolver
:param bool ignore_unresolved: allow the reference to be not defined in resolver
:param bool ignore_unresolved: do not throw if the referenced object does not exist
"""
super(_Ref, self).__init__()
assert not type(self) == _Ref, "do not instantiate _Ref directly"
@@ -530,7 +552,7 @@ class SchemaRef(_Ref):
:param .ReferenceResolver resolver: component resolver which must contain the definition
:param str schema_name: schema name
:param bool ignore_unresolved: allow the reference to be not defined in resolver
:param bool ignore_unresolved: do not throw if the referenced object does not exist
"""
assert SCHEMA_DEFINITIONS in resolver.scopes
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema, ignore_unresolved)
@@ -542,7 +564,8 @@ 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 ref_or_obj: object to derefernece
:type ref_or_obj: SwaggerDict or _Ref
:param resolver: component resolver which must contain the referenced object
"""
if isinstance(ref_or_obj, _Ref):
@@ -554,8 +577,9 @@ class Responses(SwaggerDict):
def __init__(self, responses, default=None, **extra):
"""Describes the expected responses of an :class:`.Operation`.
:param dict[(str,int),.Response] responses: mapping of status code to response definition
:param .Response default: description of the response structure to expect if another status code is returned
:param responses: mapping of status code to response definition
:type responses: dict[str or int,Response]
:param Response default: description of the response structure to expect if another status code is returned
"""
super(Responses, self).__init__(**extra)
for status, response in responses.items():
@@ -570,7 +594,9 @@ class Response(SwaggerDict):
"""Describes the structure of an operation's response.
:param str description: response description
:param .Schema,.SchemaRef schema: sturcture of the response body
:param schema: sturcture of the response body
:type schema: Schema or SchemaRef or rest_framework.serializers.Serializer
or type[rest_framework.serializers.Serializer]
:param dict examples: example bodies mapped by mime type
"""
super(Response, self).__init__(**extra)
@@ -643,7 +669,7 @@ class ReferenceResolver(object):
"""Set an object in the given scope only if it does not exist.
:param str name: reference name
:param callable maker: object factory, called only if necessary
:param function maker: object factory, called only if necessary
:param str scope: reference scope
"""
scope = self._check_scope(scope)
+17 -6
View File
@@ -1,9 +1,11 @@
import six
from django.shortcuts import render, resolve_url
from django.shortcuts import resolve_url
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.functional import Promise
from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer
from rest_framework.utils import json
from rest_framework.utils import encoders, json
from .app_settings import redoc_settings, swagger_settings
from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
@@ -31,6 +33,7 @@ class _SpecRenderer(BaseRenderer):
# in that case, it's probably better to let the default ``JSONRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58
return JSONRenderer().render(data, media_type, renderer_context)
return codec.encode(data)
@@ -67,13 +70,14 @@ class _UIRenderer(BaseRenderer):
# in that case, it's probably better to let the default ``TemplateHTMLRenderer`` render it
# see https://github.com/axnsan12/drf-yasg/issues/58
return TemplateHTMLRenderer().render(swagger, accepted_media_type, renderer_context)
self.set_context(renderer_context, swagger)
return render(renderer_context['request'], self.template, renderer_context)
return render_to_string(self.template, renderer_context, renderer_context['request'])
def set_context(self, renderer_context, swagger=None):
renderer_context['title'] = swagger.info.title or '' if swagger else ''
renderer_context['version'] = swagger.info.version or '' if swagger else ''
renderer_context['oauth2_config'] = json.dumps(self.get_oauth2_config())
renderer_context['oauth2_config'] = json.dumps(self.get_oauth2_config(), cls=encoders.JSONEncoder)
renderer_context['USE_SESSION_AUTH'] = swagger_settings.USE_SESSION_AUTH
renderer_context.update(self.get_auth_urls())
@@ -117,7 +121,14 @@ class SwaggerUIRenderer(_UIRenderer):
def set_context(self, renderer_context, swagger=None):
super(SwaggerUIRenderer, self).set_context(renderer_context, swagger)
renderer_context['swagger_settings'] = json.dumps(self.get_swagger_ui_settings())
swagger_ui_settings = self.get_swagger_ui_settings()
request = renderer_context.get('request', None)
oauth_redirect_url = force_text(swagger_ui_settings.get('oauth2RedirectUrl', ''))
if request and oauth_redirect_url:
swagger_ui_settings['oauth2RedirectUrl'] = request.build_absolute_uri(oauth_redirect_url)
renderer_context['swagger_settings'] = json.dumps(swagger_ui_settings, cls=encoders.JSONEncoder)
def get_swagger_ui_settings(self):
data = {
@@ -154,7 +165,7 @@ class ReDocRenderer(_UIRenderer):
def set_context(self, renderer_context, swagger=None):
super(ReDocRenderer, self).set_context(renderer_context, swagger)
renderer_context['redoc_settings'] = json.dumps(self.get_redoc_settings())
renderer_context['redoc_settings'] = json.dumps(self.get_redoc_settings(), cls=encoders.JSONEncoder)
def get_redoc_settings(self):
data = {
File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

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
@@ -2,6 +2,17 @@
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
var defaultSpecUrl = currentPath + '?format=openapi';
function slugify(text) {
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/--+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
var KEY_AUTH = slugify(window.location.pathname) + "-drf-yasg-auth";
// load the saved authorization state from localStorage; ImmutableJS is used for consistency with swagger-ui state
var savedAuth = Immutable.fromJS({});
@@ -56,8 +67,7 @@ function initSwaggerUi() {
}
if (document.querySelector('.auth-wrapper .authorize')) {
patchSwaggerUi();
}
else {
} else {
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
}
@@ -114,9 +124,9 @@ function initSwaggerUiConfig(swaggerSettings, oauth2Settings) {
}
if (persistAuth) {
try {
savedAuth = Immutable.fromJS(JSON.parse(localStorage.getItem("drf-yasg-auth")) || {});
savedAuth = Immutable.fromJS(JSON.parse(localStorage.getItem(KEY_AUTH)) || {});
} catch (e) {
localStorage.removeItem("drf-yasg-auth");
localStorage.removeItem(KEY_AUTH);
}
}
if (refetchWithAuth) {
@@ -182,7 +192,6 @@ function initSwaggerUiConfig(swaggerSettings, oauth2Settings) {
var oldResponseInterceptor = swaggerUiConfig.responseInterceptor;
swaggerUiConfig.responseInterceptor = function (response) {
var absUrl = new URL(response.url, currentPath);
console.log("response", response);
if (absUrl.href in specRequestsInFlight) {
var setToUrl = specRequestsInFlight[absUrl.href];
delete specRequestsInFlight[absUrl.href];
@@ -278,8 +287,7 @@ function applyAuth(authorization, requestUrl, requestHeaders) {
if (_in === "query") {
if (requestUrl) {
requestUrl = setQueryParam(requestUrl, paramName, key);
}
else {
} else {
console.warn("WARNING: cannot apply apiKey query parameter via interceptor");
}
}
@@ -343,7 +351,7 @@ function hookAuthActions(sui, persistAuth, refetchWithAuth, refetchOnLogout) {
sui.authActions.showDefinitions(); // hide authorize dialog
}
if (persistAuth) {
localStorage.setItem("drf-yasg-auth", JSON.stringify(savedAuth.toJSON()));
localStorage.setItem(KEY_AUTH, JSON.stringify(savedAuth.toJSON()));
}
};
@@ -368,7 +376,7 @@ function hookAuthActions(sui, persistAuth, refetchWithAuth, refetchOnLogout) {
sui.authActions.showDefinitions(); // hide authorize dialog
}
if (persistAuth) {
localStorage.setItem("drf-yasg-auth", JSON.stringify(savedAuth.toJSON()));
localStorage.setItem(KEY_AUTH, JSON.stringify(savedAuth.toJSON()));
}
originalLogout(authorization);
};
+59 -24
View File
@@ -29,7 +29,7 @@ class unset(object):
def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_body=None, query_serializer=None,
manual_parameters=None, operation_id=None, operation_description=None, operation_summary=None,
security=None, deprecated=None, responses=None, field_inspectors=None, filter_inspectors=None,
paginator_inspectors=None, **extra_overrides):
paginator_inspectors=None, tags=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
@@ -39,11 +39,11 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
: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;
:param drf_yasg.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, and can be set to ``None`` to prevent this operation from being generated
:param .Schema,.SchemaRef,.Serializer request_body: custom request body, or :class:`.no_body`. The value given here
will be used as the ``schema`` property of a :class:`.Parameter` with ``in: 'body'``.
:param request_body: custom request body which 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
@@ -51,9 +51,11 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
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.
:type request_body: drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or rest_framework.serializers.Serializer
or type[no_body]
: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.
:param rest_framework.serializers.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.
@@ -61,7 +63,8 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
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
:param list[drf_yasg.openapi.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.
@@ -75,7 +78,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
authentication schemes), and ``None`` will inherit the top-level secuirty requirements
:param bool deprecated: deprecation status for operation
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
:param 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.
@@ -89,13 +92,16 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
* 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`
:type responses: dict[str,(drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or drf_yasg.openapi.Response or
str or rest_framework.serializers.Serializer)]
: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 list[type[drf_yasg.inspectors.FieldInspector]] field_inspectors: extra serializer and field inspectors; these
will be tried before :attr:`.ViewInspector.field_inspectors` on the :class:`.inspectors.SwaggerAutoSchema`
:param list[type[drf_yasg.inspectors.FilterInspector]] filter_inspectors: extra filter inspectors; these will be
tried before :attr:`.ViewInspector.filter_inspectors` on the :class:`.inspectors.SwaggerAutoSchema`
:param list[type[drf_yasg.inspectors.PaginatorInspector]] paginator_inspectors: extra paginator inspectors; these
will be tried before :attr:`.ViewInspector.paginator_inspectors` on the :class:`.inspectors.SwaggerAutoSchema`
:param list[str] tags: tags override
: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``
"""
@@ -115,6 +121,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=unset, request_bo
'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,
'tags': list(tags) if tags else None,
}
data = filter_none(data)
if auto_schema is not unset:
@@ -207,7 +214,7 @@ def is_list_view(path, method, view):
"""
# for ViewSets, it could be the default 'list' action, or a list_route
action = getattr(view, 'action', '')
method = getattr(view, action, None)
method = getattr(view, action, None) or method
detail = getattr(method, 'detail', None)
suffix = getattr(view, 'suffix', None)
if action in ('list', 'create') or detail is False or suffix == 'List':
@@ -245,9 +252,9 @@ def param_list_to_odict(parameters):
Raises an ``AssertionError`` if `parameters` contains duplicate parameters (by their name + in combination).
:param list[.Parameter] parameters: the list of parameters
:param list[drf_yasg.openapi.Parameter] parameters: the list of parameters
:return: `parameters` keyed by ``(name, in_)``
:rtype: dict[tuple(str,str),.Parameter]
:rtype: dict[(str,str),drf_yasg.openapi.Parameter]
"""
result = OrderedDict(((param.name, param.in_), param) for param in parameters)
assert len(result) == len(parameters), "duplicate Parameters found"
@@ -260,10 +267,10 @@ def merge_params(parameters, overrides):
Raises an ``AssertionError`` if either list contains duplicate parameters.
:param list[.Parameter] parameters: initial parameters
:param list[.Parameter] overrides: overriding parameters
:param list[drf_yasg.openapi.Parameter] parameters: initial parameters
:param list[drf_yasg.openapi.Parameter] overrides: overriding parameters
:return: merged list
:rtype: list[.Parameter]
:rtype: list[drf_yasg.openapi.Parameter]
"""
parameters = param_list_to_odict(parameters)
parameters.update(param_list_to_odict(overrides))
@@ -293,6 +300,7 @@ def force_serializer_instance(serializer):
an assertion error.
:param serializer: serializer class or instance
:type serializer: serializers.BaseSerializer or type[serializers.BaseSerializer]
:return: serializer instance
:rtype: serializers.BaseSerializer
"""
@@ -325,28 +333,55 @@ def get_serializer_class(serializer):
return type(serializer)
def get_object_classes(classes_or_instances, expected_base_class=None):
"""Given a list of instances or class objects, return the list of their classes.
:param classes_or_instances: mixed list to parse
:type classes_or_instances: list[type or object]
:param expected_base_class: if given, only subclasses or instances of this type will be returned
:type expected_base_class: type
:return: list of classes
:rtype: list
"""
classes_or_instances = classes_or_instances or []
result = []
for obj in classes_or_instances:
if inspect.isclass(obj):
if not expected_base_class or issubclass(obj, expected_base_class):
result.append(obj)
else:
if not expected_base_class or isinstance(obj, expected_base_class):
result.append(type(obj))
return result
def get_consumes(parser_classes):
"""Extract ``consumes`` MIME types from a list of parser classes.
:param list parser_classes: parser classes
:type parser_classes: list[rest_framework.parsers.BaseParser or type[rest_framework.parsers.BaseParser]]
:return: MIME types for ``consumes``
:rtype: list[str]
"""
parser_classes = get_object_classes(parser_classes)
media_types = [parser.media_type for parser in parser_classes or []]
if all(is_form_media_type(encoding) for encoding in media_types):
non_form_media_types = [encoding for encoding in media_types if not is_form_media_type(encoding)]
if len(non_form_media_types) == 0:
return media_types
else:
media_types = [encoding for encoding in media_types if not is_form_media_type(encoding)]
return media_types
return non_form_media_types
def get_produces(renderer_classes):
"""Extract ``produces`` MIME types from a list of renderer classes.
:param list renderer_classes: renderer classes
:type renderer_classes: list[rest_framework.renderers.BaseRenderer or type[rest_framework.renderers.BaseRenderer]]
:return: MIME types for ``produces``
:rtype: list[str]
"""
renderer_classes = get_object_classes(renderer_classes)
media_types = [renderer.media_type for renderer in renderer_classes or []]
media_types = [encoding for encoding in media_types
if not any(excluded in encoding for excluded in swagger_settings.EXCLUDED_MEDIA_TYPES)]
@@ -371,7 +406,7 @@ def get_serializer_ref_name(serializer):
:param serializer: Serializer instance
:return: Serializer's ``ref_name`` or ``None`` for inline serializer
:rtype: str
:rtype: str or None
"""
serializer_meta = getattr(serializer, 'Meta', None)
serializer_name = type(serializer).__name__
+4 -4
View File
@@ -62,7 +62,7 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
:param tuple authentication_classes: authentication classes for the schema view itself
:param tuple permission_classes: permission classes for the schema view itself
:return: SchemaView class
:rtype: type[.SchemaView]
:rtype: type[drf_yasg.views.SchemaView]
"""
_public = public
_generator_class = generator_class or swagger_settings.DEFAULT_GENERATOR_CLASS
@@ -112,7 +112,7 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
def as_cached_view(cls, cache_timeout=0, cache_kwargs=None, **initkwargs):
"""
Calls .as_view() and wraps the result in a cache_page decorator.
See https://docs.djangoproject.com/en/1.11/topics/cache/
See https://docs.djangoproject.com/en/dev/topics/cache/
:param int cache_timeout: same as cache_page; set to 0 for no cache
:param dict cache_kwargs: dictionary of kwargs to be passed to cache_page
@@ -131,7 +131,7 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
def without_ui(cls, cache_timeout=0, cache_kwargs=None):
"""
Instantiate this view with just JSON and YAML renderers, optionally wrapped with cache_page.
See https://docs.djangoproject.com/en/1.11/topics/cache/.
See https://docs.djangoproject.com/en/dev/topics/cache/.
:param int cache_timeout: same as cache_page; set to 0 for no cache
:param dict cache_kwargs: dictionary of kwargs to be passed to cache_page
@@ -143,7 +143,7 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
def with_ui(cls, renderer='swagger', cache_timeout=0, cache_kwargs=None):
"""
Instantiate this view with a Web UI renderer, optionally wrapped with cache_page.
See https://docs.djangoproject.com/en/1.11/topics/cache/.
See https://docs.djangoproject.com/en/dev/topics/cache/.
:param str renderer: UI renderer; allowed values are ``swagger``, ``redoc``
:param int cache_timeout: same as cache_page; set to 0 for no cache
+1
View File
@@ -33,6 +33,7 @@ class ArticleSerializer(serializers.ModelSerializer):
class ImageUploadSerializer(serializers.Serializer):
image_id = serializers.UUIDField(read_only=True)
what_am_i_doing = serializers.RegexField(
regex=r"^69$",
help_text="test",
+31 -39
View File
@@ -1,10 +1,10 @@
import datetime
import functools
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
# noinspection PyDeprecation
from rest_framework.decorators import detail_route, list_route
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.parsers import MultiPartParser
@@ -62,7 +62,7 @@ class ArticlePagination(LimitOffsetPagination):
@method_decorator(name='list', decorator=swagger_auto_schema(
operation_description="description from swagger_auto_schema via method_decorator",
filter_inspectors=[DjangoFilterDescriptionInspector]
filter_inspectors=[DjangoFilterDescriptionInspector],
))
class ArticleViewSet(viewsets.ModelViewSet):
"""
@@ -84,7 +84,10 @@ class ArticleViewSet(viewsets.ModelViewSet):
pagination_class = ArticlePagination
filter_backends = (DjangoFilterBackend, OrderingFilter)
filter_fields = ('title',)
filterset_fields = ('title',)
# django-filter 1.1 compatibility; was renamed to filterset_fields in 2.0
# TODO: remove when dropping support for Django 1.11
filter_fields = filterset_fields
ordering_fields = ('date_modified', 'date_created')
ordering = ('date_created',)
@@ -92,46 +95,35 @@ class ArticleViewSet(viewsets.ModelViewSet):
try:
from rest_framework.decorators import action
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@action(detail=False, methods=['get'])
def today(self, request):
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
serializer = self.serializer_class(articles, many=True)
return Response(serializer.data)
@swagger_auto_schema(method='get', operation_description="image GET description override")
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
@action(detail=True, methods=['get', 'post'], parser_classes=(MultiPartParser,))
def image(self, request, slug=None):
"""
image method docstring
"""
pass
list_route = functools.partial(action, detail=False)
detail_route = functools.partial(action, detail=True)
except ImportError:
# TODO: remove when dropping support for DRF 3.7
action = None
from rest_framework.decorators import list_route, detail_route
# noinspection PyDeprecation
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@list_route(methods=['get'])
def today(self, request):
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
serializer = self.serializer_class(articles, many=True)
return Response(serializer.data)
@swagger_auto_schema(auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@list_route(methods=['get'])
def today(self, request):
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
articles = self.get_queryset().filter(date_created__range=(today_min, today_max)).all()
serializer = self.serializer_class(articles, many=True)
return Response(serializer.data)
# noinspection PyDeprecation
@swagger_auto_schema(method='get', operation_description="image GET description override")
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
@detail_route(methods=['get', 'post'], parser_classes=(MultiPartParser,))
def image(self, request, slug=None):
"""
image method docstring
"""
pass
@swagger_auto_schema(method='get', operation_description="image GET description override")
@swagger_auto_schema(method='post', request_body=serializers.ImageUploadSerializer)
@swagger_auto_schema(method='delete', manual_parameters=[openapi.Parameter(
name='delete_form_param', in_=openapi.IN_FORM,
type=openapi.TYPE_INTEGER,
description="this should not crash (form parameter on DELETE method)"
)])
@detail_route(methods=['get', 'post', 'delete'], parser_classes=(MultiPartParser,))
def image(self, request, slug=None):
"""
image method docstring
"""
pass
@swagger_auto_schema(request_body=no_body, operation_id='no_body_test')
def update(self, request, *args, **kwargs):
-15
View File
@@ -1,15 +0,0 @@
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))
-3
View File
@@ -7,9 +7,6 @@ if __name__ == "__main__":
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django # noqa: F401
except ImportError:
File diff suppressed because one or more lines are too long
-5
View File
@@ -83,11 +83,6 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
description="path parameter override",
required=True
),
openapi.Parameter(
name='delete_form_param', in_=openapi.IN_FORM,
type=openapi.TYPE_INTEGER,
description="this should not crash (form parameter on DELETE method)"
),
],
responses={
status.HTTP_204_NO_CONTENT: openapi.Response(
+29 -14
View File
@@ -3,6 +3,8 @@ import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from django.urls import reverse_lazy
from testproj.util import static_lazy
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ALLOWED_HOSTS = [
@@ -22,6 +24,7 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'oauth2_provider',
'corsheaders',
'drf_yasg',
@@ -64,9 +67,9 @@ TEMPLATES = [
WSGI_APPLICATION = 'testproj.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
LOGIN_URL = reverse_lazy('admin:login')
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
@@ -83,15 +86,22 @@ AUTH_PASSWORD_VALIDATORS = [
]
# Django Rest Framework
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
# drf-yasg
OAUTH2_CLIENT_ID = '12ee6bgxtpSEgP8TioWcHSXOiDBOUrVav4mRbVEs'
OAUTH2_CLIENT_SECRET = '5FvYALo7W4uNnWE2ySw7Yzpkxh9PSf5GuY37RvOys00ydEyph64dbl1ECOKI9ceQ' \
'AKoz0JpiVQtq0DUnsxNhU3ubrJgZ9YbtiXymbLGJq8L7n4fiER7gXbXaNSbze3BN'
OAUTH2_APP_NAME = 'drf-yasg OAuth2 provider'
OAUTH2_REDIRECT_URL = static_lazy('drf-yasg/swagger-ui-dist/oauth2-redirect.html')
OAUTH2_AUTHORIZE_URL = reverse_lazy('oauth2_provider:authorize')
OAUTH2_TOKEN_URL = reverse_lazy('oauth2_provider:token')
# drf-yasg
SWAGGER_SETTINGS = {
'LOGIN_URL': reverse_lazy('admin:login'),
'LOGOUT_URL': '/admin/logout',
@@ -114,7 +124,22 @@ SWAGGER_SETTINGS = {
'type': 'apiKey',
'name': 'auth',
'in': 'query'
},
'OAuth2 password': {
'type': 'oauth2',
'flow': 'password',
'tokenUrl': OAUTH2_TOKEN_URL,
'scopes': {
'read': 'Read everything.',
'write': 'Write everything,',
}
}
},
'OAUTH2_REDIRECT_URL': OAUTH2_REDIRECT_URL,
'OAUTH2_CONFIG': {
'clientId': OAUTH2_CLIENT_ID,
'clientSecret': OAUTH2_CLIENT_SECRET,
'appName': OAUTH2_APP_NAME,
}
}
@@ -123,21 +148,13 @@ REDOC_SETTINGS = {
}
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
@@ -145,11 +162,9 @@ STATICFILES_DIRS = [
]
# Testing
TEST_RUNNER = 'testproj.runner.PytestTestRunner'
# Logging configuration
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
-2
View File
@@ -23,8 +23,6 @@ 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)
}
-1
View File
@@ -15,7 +15,6 @@ DATABASES = {
}
# 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'
View File
+7 -2
View File
@@ -47,6 +47,12 @@ def root_redirect(request):
return redirect(schema_view, permanent=True)
# urlpatterns required for settings values
required_urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
urlpatterns = [
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
@@ -59,11 +65,10 @@ urlpatterns = [
url(r'^$', root_redirect),
url(r'^admin/', admin.site.urls),
url(r'^snippets/', include('snippets.urls')),
url(r'^articles/', include('articles.urls')),
url(r'^users/', include('users.urls')),
url(r'^todo/', include('todo.urls')),
url(r'^people/', include('people.urls')),
url(r'^plain/', plain_view),
]
] + required_urlpatterns
+4
View File
@@ -0,0 +1,4 @@
from django.templatetags.static import static
from django.utils.functional import lazy
static_lazy = lazy(static, str)
@@ -0,0 +1,37 @@
# Generated by Django 2.1.3 on 2018-12-19 08:07
import sys
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.db import migrations, IntegrityError
def add_default_user(apps, schema_editor):
username = 'admin'
email = 'admin@admin.admin'
password = 'passwordadmin'
User = apps.get_model(settings.AUTH_USER_MODEL)
try:
admin = User(
username=username,
email=email,
password=make_password(password),
is_superuser=True,
is_staff=True
)
admin.save()
except IntegrityError:
sys.stdout.write(" User '%s <%s>' already exists..." % (username, email))
else:
sys.stdout.write(" Created superuser '%s <%s>' with password '%s'!" % (username, email, password))
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.RunPython(add_default_user)
]
@@ -0,0 +1,39 @@
# Generated by Django 2.1.3 on 2018-12-19 07:57
from django.conf import settings
from django.db import migrations
def add_oauth_apps(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
User = apps.get_model(settings.AUTH_USER_MODEL)
Application = apps.get_model('oauth2_provider', 'application')
user = User.objects.get(username='admin')
oauth2_apps = [
{
"user": user,
"client_type": "public",
"authorization_grant_type": "password",
"client_id": settings.OAUTH2_CLIENT_ID,
"client_secret": settings.OAUTH2_CLIENT_SECRET,
"redirect_uris": settings.OAUTH2_REDIRECT_URL,
"name": settings.OAUTH2_APP_NAME
}
]
for app in oauth2_apps:
Application.objects.get_or_create(client_id=app['client_id'], defaults=app)
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('oauth2_provider', '0006_auto_20171214_2232'),
('users', '0001_create_admin_user'),
]
operations = [
migrations.RunPython(add_oauth_apps)
]
+1
View File
@@ -81,3 +81,4 @@ class UserSerializerrr(serializers.ModelSerializer):
class UserListQuerySerializer(serializers.Serializer):
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)
styles = serializers.MultipleChoiceField(help_text="and this one is fancy!", choices=('a', 'b', 'c', 'd'))
+12 -5
View File
@@ -13,7 +13,11 @@ from users.serializers import UserListQuerySerializer, UserSerializerrr
class UserList(APIView):
"""UserList cbv classdoc"""
@swagger_auto_schema(query_serializer=UserListQuerySerializer, responses={200: UserSerializerrr(many=True)})
@swagger_auto_schema(
query_serializer=UserListQuerySerializer,
responses={200: UserSerializerrr(many=True)},
tags=['Users'],
)
def get(self, request):
queryset = User.objects.all()
serializer = UserSerializerrr(queryset, many=True)
@@ -28,7 +32,8 @@ class UserList(APIView):
'username': openapi.Schema(type=openapi.TYPE_STRING)
},
),
security=[]
security=[],
tags=['Users'],
)
def post(self, request):
serializer = UserSerializerrr(request.data)
@@ -36,17 +41,19 @@ class UserList(APIView):
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
@swagger_auto_schema(operation_id="users_dummy", operation_description="dummy operation")
@swagger_auto_schema(operation_id="users_dummy", operation_description="dummy operation", tags=['Users'])
def patch(self, request):
pass
@swagger_auto_schema(method='put', request_body=UserSerializerrr)
@swagger_auto_schema(method='put', request_body=UserSerializerrr, tags=['Users'])
@swagger_auto_schema(methods=['get'], manual_parameters=[
openapi.Parameter('test', openapi.IN_QUERY, "test manual param", type=openapi.TYPE_BOOLEAN),
openapi.Parameter('test_array', openapi.IN_QUERY, "test query array arg", type=openapi.TYPE_ARRAY,
items=openapi.Items(type=openapi.TYPE_STRING), required=True, collection_format='multi'),
], responses={
200: openapi.Response('response description', UserSerializerrr),
})
}, tags=['Users'])
@api_view(['GET', 'PUT'])
def user_detail(request, pk):
"""user_detail fbv docstring"""
+2 -3
View File
@@ -22,8 +22,7 @@ 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)
user = User.objects.get(username='admin')
request = factory.get('/swagger.json')
force_authenticate(request, user=user)
request = APIView().initialize_request(request)
@@ -56,7 +55,7 @@ def swagger_dict(swagger, codec_json):
@pytest.fixture
def validate_schema(db):
def validate_schema():
def validate_schema(swagger):
from flex.core import parse as validate_flex
from swagger_spec_validator.validator20 import validate_spec as validate_ssv
+58 -9
View File
@@ -27,6 +27,13 @@ securityDefinitions:
in: header
name: Authorization
type: apiKey
OAuth2 password:
flow: password
scopes:
read: Read everything.
write: Write everything,
tokenUrl: /o/token/
type: oauth2
Query:
in: query
name: auth
@@ -34,6 +41,7 @@ securityDefinitions:
security:
- Basic: []
- Bearer: []
- OAuth2 password: []
- Query: []
paths:
/articles/:
@@ -75,9 +83,11 @@ paths:
next:
type: string
format: uri
x-nullable: true
previous:
type: string
format: uri
x-nullable: true
results:
type: array
items:
@@ -239,6 +249,21 @@ paths:
- multipart/form-data
tags:
- articles
delete:
operationId: articles_image_delete
description: image method docstring
parameters:
- name: delete_form_param
in: formData
description: this should not crash (form parameter on DELETE method)
type: integer
responses:
'204':
description: ''
consumes:
- multipart/form-data
tags:
- articles
parameters:
- name: slug
in: path
@@ -468,10 +493,6 @@ paths:
description: path parameter override
required: true
type: integer
- name: delete_form_param
in: formData
description: this should not crash (form parameter on DELETE method)
type: integer
responses:
'204':
description: this should not crash (response object with no schema)
@@ -740,6 +761,19 @@ paths:
description: this one too!
required: false
type: boolean
- name: styles
in: query
description: and this one is fancy!
required: true
type: array
items:
type: string
enum:
- a
- b
- c
- d
collectionFormat: multi
responses:
'200':
description: ''
@@ -748,7 +782,7 @@ paths:
items:
$ref: '#/definitions/UserSerializerrr'
tags:
- users
- Users
post:
operationId: users_create
description: apiview post description override
@@ -774,7 +808,7 @@ paths:
username:
type: string
tags:
- users
- Users
security: []
patch:
operationId: users_dummy
@@ -784,7 +818,7 @@ paths:
'200':
description: ''
tags:
- users
- Users
parameters: []
/users/{id}/:
get:
@@ -795,13 +829,21 @@ paths:
in: query
description: test manual param
type: boolean
- name: test_array
in: query
description: test query array arg
required: true
type: array
items:
type: string
collectionFormat: multi
responses:
'200':
description: response description
schema:
$ref: '#/definitions/UserSerializerrr'
tags:
- users
- Users
put:
operationId: users_update
description: user_detail fbv docstring
@@ -817,7 +859,7 @@ paths:
schema:
$ref: '#/definitions/UserSerializerrr'
tags:
- users
- Users
parameters:
- name: id
in: path
@@ -904,6 +946,10 @@ definitions:
- image_styles
type: object
properties:
image_id:
type: string
format: uuid
readOnly: true
what_am_i_doing:
description: test
type: string
@@ -1159,6 +1205,7 @@ definitions:
- fan
- fancy
- felix
- fennel
- fish
- flatline
- forth
@@ -1184,6 +1231,7 @@ definitions:
- haskell
- haxeml
- hexdump
- hlsl
- hsail
- html
- html+cheetah
@@ -1450,6 +1498,7 @@ definitions:
- xml+php
- xml+smarty
- xml+velocity
- xorg.conf
- xquery
- xslt
- xtend
+44
View File
@@ -0,0 +1,44 @@
import pytest
from django.conf.urls import url
from django.utils.decorators import method_decorator
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from drf_yasg import openapi
from drf_yasg.errors import SwaggerGenerationError
from drf_yasg.generators import OpenAPISchemaGenerator
from drf_yasg.utils import swagger_auto_schema
def test_no_form_parameters_with_non_form_parsers():
# see https://github.com/axnsan12/drf-yasg/issues/270
# test that manual form parameters for views that haven't set
# all their parsers classes to form parsers are not allowed
# even when the request body is empty
@method_decorator(name='post', decorator=swagger_auto_schema(
operation_description="Logins a user and returns a token",
manual_parameters=[
openapi.Parameter(
"username",
openapi.IN_FORM,
required=True,
type=openapi.TYPE_STRING,
description="Valid username or email for authentication"
),
]
))
class CustomObtainAuthToken(ObtainAuthToken):
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
urlpatterns = [
url(r'token/$', CustomObtainAuthToken.as_view()),
]
generator = OpenAPISchemaGenerator(
info=openapi.Info(title="Test generator", default_version="v1"),
patterns=urlpatterns
)
with pytest.raises(SwaggerGenerationError):
generator.get_schema(None, True)
-3
View File
@@ -6,7 +6,6 @@ import tempfile
from collections import OrderedDict
import pytest
from django.contrib.auth.models import User
from drf_yasg import openapi
from drf_yasg.codecs import yaml_sane_load
@@ -14,8 +13,6 @@ from drf_yasg.generators import OpenAPISchemaGenerator
def test_reference_schema(call_generate_swagger, db, reference_schema):
User.objects.create_superuser('admin', 'admin@admin.admin', 'blabla')
output = call_generate_swagger(format='yaml', api_url='http://test.local:8002/', user='admin')
output_schema = yaml_sane_load(output)
assert output_schema == reference_schema
+42 -3
View File
@@ -3,6 +3,7 @@ from collections import OrderedDict
import pytest
from django.conf.urls import url
from django.utils.inspect import get_func_args
from rest_framework import routers, serializers, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
@@ -86,6 +87,14 @@ def test_securiy_requirements(swagger_settings, mock_schema_request):
assert swagger['security'] == []
def _basename_or_base_name(basename):
# freaking DRF... TODO: remove when dropping support for DRF 3.8
if 'basename' in get_func_args(routers.BaseRouter.register):
return {'basename': basename}
else:
return {'base_name': basename}
def test_replaced_serializer():
class DetailSerializer(serializers.Serializer):
detail = serializers.CharField()
@@ -99,7 +108,7 @@ def test_replaced_serializer():
return Response(serializer.data)
router = routers.DefaultRouter()
router.register(r'details', DetailViewSet, base_name='details')
router.register(r'details', DetailViewSet, **_basename_or_base_name('details'))
generator = OpenAPISchemaGenerator(
info=openapi.Info(title="Test generator", default_version="v1"),
@@ -146,7 +155,8 @@ def test_url_order():
assert swagger['paths']['/test/']['get']['description'] == 'description override'
# get_endpoints only includes one endpoint
assert len(generator.get_endpoints(None)['/test/'][1]) == 1
endpoints = generator.get_endpoints(None)
assert len(endpoints['/test/'][1]) == 1
try:
@@ -172,7 +182,7 @@ def test_action_mapping():
pass
router = routers.DefaultRouter()
router.register(r'action', ActionViewSet, base_name='action')
router.register(r'action', ActionViewSet, **_basename_or_base_name('action'))
generator = OpenAPISchemaGenerator(
info=openapi.Info(title="Test generator", default_version="v1"),
@@ -190,3 +200,32 @@ def test_action_mapping():
assert action_ops['post']['description'] == 'mapping docstring post'
assert action_ops['get']['description'] == 'mapping docstring get/delete'
assert action_ops['delete']['description'] == 'mapping docstring get/delete'
@pytest.mark.parametrize('choices, expected_type', [
(['A', 'B'], openapi.TYPE_STRING),
([123, 456], openapi.TYPE_INTEGER),
([1.2, 3.4], openapi.TYPE_NUMBER),
(['A', 456], openapi.TYPE_STRING)
])
def test_choice_field(choices, expected_type):
class DetailSerializer(serializers.Serializer):
detail = serializers.ChoiceField(choices)
class DetailViewSet(viewsets.ViewSet):
@swagger_auto_schema(responses={200: openapi.Response("OK", DetailSerializer)})
def retrieve(self, request, pk=None):
return Response({'detail': None})
router = routers.DefaultRouter()
router.register(r'details', DetailViewSet, **_basename_or_base_name('details'))
generator = OpenAPISchemaGenerator(
info=openapi.Info(title="Test generator", default_version="v1"),
patterns=router.urls
)
swagger = generator.get_schema(None, True)
property_schema = swagger['definitions']['Detail']['properties']['detail']
assert property_schema == openapi.Schema(title='Detail', type=expected_type, enum=choices)
+3 -1
View File
@@ -1,11 +1,13 @@
from django.conf.urls import url
from testproj.urls import required_urlpatterns
def dummy(request):
pass
urlpatterns = [
urlpatterns = required_urlpatterns + [
url(r'^test/login$', dummy, name='login'),
url(r'^test/logout$', dummy, name='logout'),
]
+2 -1
View File
@@ -3,6 +3,7 @@ from rest_framework import generics, versioning
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from testproj.urls import required_urlpatterns
class SnippetList(generics.ListCreateAPIView):
@@ -21,6 +22,6 @@ class SnippetList(generics.ListCreateAPIView):
app_name = 'test_ns_versioning'
urlpatterns = [
urlpatterns = required_urlpatterns + [
url(r"^$", SnippetList.as_view())
]
+2 -1
View File
@@ -2,6 +2,7 @@ from django.conf.urls import url
from rest_framework import fields
from snippets.serializers import SnippetSerializer
from testproj.urls import required_urlpatterns
from .ns_version1 import SnippetList as SnippetListV1
@@ -19,6 +20,6 @@ class SnippetListV2(SnippetListV1):
app_name = '2.0'
urlpatterns = [
urlpatterns = required_urlpatterns + [
url(r"^$", SnippetListV2.as_view())
]
+2 -2
View File
@@ -1,7 +1,7 @@
from django.conf.urls import include, url
from rest_framework import versioning
from testproj.urls import SchemaView
from testproj.urls import SchemaView, required_urlpatterns
from . import ns_version1, ns_version2
@@ -17,7 +17,7 @@ schema_patterns = [
]
urlpatterns = [
urlpatterns = required_urlpatterns + [
url(VERSION_PREFIX_NS + r"v1.0/snippets/", include(ns_version1, namespace='1.0')),
url(VERSION_PREFIX_NS + r"v2.0/snippets/", include(ns_version2)),
url(VERSION_PREFIX_NS + r'v1.0/', include((schema_patterns, '1.0'))),
+2 -2
View File
@@ -3,7 +3,7 @@ from rest_framework import fields, generics, versioning
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from testproj.urls import SchemaView
from testproj.urls import SchemaView, required_urlpatterns
class SnippetSerializerV2(SnippetSerializer):
@@ -42,7 +42,7 @@ class VersionedSchemaView(SchemaView):
versioning_class = versioning.URLPathVersioning
urlpatterns = [
urlpatterns = required_urlpatterns + [
url(VERSION_PREFIX_URL + r"snippets/$", SnippetList.as_view()),
url(VERSION_PREFIX_URL + r'swagger(?P<format>.json|.yaml)$', VersionedSchemaView.without_ui(), name='vschema-json'),
]
+21 -14
View File
@@ -1,11 +1,19 @@
[tox]
minversion = 3.3.0
isolated_build = true
isolated_build_env=.package
# https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django
envlist =
py{27,34,35,36}-django111-drf{37,38},
py{34,35,36,37}-django20-drf{37,38},
py{35,36,37}-django21-drf{37,38},
py{27,34,35,36}-django111-drf{37,38,39},
py{34,35,36,37}-django20-drf{37,38,39},
py{35,36,37}-django21-drf{37,38,39},
djmaster, lint, docs
[testenv:.package]
# no additional dependencies besides PEP 517
deps =
[testenv]
deps =
django111: Django>=1.11,<2.0
@@ -14,43 +22,42 @@ deps =
drf37: djangorestframework>=3.7.7,<3.8
drf38: djangorestframework>=3.8.0,<3.9
drf39: djangorestframework>=3.9,<3.10
# test with the latest build of django-rest-framework to get early warning of compatibility issues
djmaster: https://github.com/encode/django-rest-framework/archive/master.tar.gz
djmaster: https://github.com/django/django/archive/master.tar.gz
# other dependencies
-rrequirements/setup.txt
-rrequirements/validation.txt
-rrequirements/test.txt
-r requirements/validation.txt
-r requirements/test.txt
commands =
pytest --cov --cov-config .coveragerc --cov-append --cov-report="" {posargs}
pytest -n 2 --cov --cov-config .coveragerc --cov-append --cov-report="" {posargs}
[testenv:lint]
skip_install = true
deps =
-rrequirements/lint.txt
-r requirements/lint.txt
commands =
flake8 src/drf_yasg testproj tests setup.py
[testenv:docs]
deps =
-rrequirements/setup.txt
-rrequirements/docs.txt
-r requirements/docs.txt
commands =
python setup.py check --restructuredtext --metadata --strict
twine check .tox/dist/*
sphinx-build -WnEa -b html docs docs/_build/html
[pytest]
DJANGO_SETTINGS_MODULE = testproj.settings.local
python_paths = testproj
addopts = -n 2 --ignore=node_modules
addopts = --ignore=node_modules
[flake8]
max-line-length = 120
exclude = **/migrations/*
ignore = F405
ignore = F405,W504
[isort]
skip = .eggs,.tox,docs,env,venv,node_modules
@@ -66,5 +73,5 @@ known_standard_library =
known_third_party =
coreapi,coreschema,datadiff,dj_database_url,django,django_filters,djangorestframework_camel_case,
rest_framework_recursive,flex,gunicorn,inflection,pygments,pytest,rest_framework,ruamel,setuptools_scm,
swagger_spec_validator,uritemplate,user_agents,whitenoise
swagger_spec_validator,uritemplate,user_agents,whitenoise,oauth2_provider
known_first_party = drf_yasg,testproj,articles,people,snippets,todo,users,urlconfs