Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a46b684fea | |||
| fc35d9043e | |||
| f18ff60ae7 | |||
| a82730d32b | |||
| e30af0287f | |||
| fc253665dd | |||
| 33199aec59 | |||
| 9d1150f1ab | |||
| bc4037f721 | |||
| 6c4dcb18bb | |||
| 4445137d55 | |||
| 57870d12a4 | |||
| 7a3fe8ec0c | |||
| 757d47e1c0 | |||
| 59a51ba4a7 | |||
| 55223e32e2 | |||
| 6a478e14d7 | |||
| 57d77cc48a | |||
| c225f66fb7 | |||
| 47de6f2f6f | |||
| 8dbf3fe984 | |||
| 1c3fba6e54 | |||
| c4379dc6a7 | |||
| 6b38a3b6c1 | |||
| 464a518ae5 | |||
| 15c67891c6 | |||
| 917ccd1f56 | |||
| fd099998ea | |||
| a6e24e20c3 | |||
| 6608e0050c |
+7
-1
@@ -1,6 +1,8 @@
|
||||
[run]
|
||||
source = drf_yasg
|
||||
branch = True
|
||||
parallel = true
|
||||
disable_warnings = module-not-measured
|
||||
|
||||
[report]
|
||||
# Regexes for lines to exclude from consideration
|
||||
@@ -18,7 +20,10 @@ exclude_lines =
|
||||
raise TypeError
|
||||
raise NotImplementedError
|
||||
warnings.warn
|
||||
logger.debug
|
||||
logger.info
|
||||
logger.warning
|
||||
logger.error
|
||||
return NotHandled
|
||||
|
||||
# Don't complain if non-runnable code isn't run:
|
||||
@@ -29,7 +34,8 @@ exclude_lines =
|
||||
raise SwaggerGenerationError
|
||||
|
||||
ignore_errors = True
|
||||
precision = 0
|
||||
precision = 2
|
||||
show_missing = True
|
||||
|
||||
[paths]
|
||||
source =
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
node_modules/
|
||||
testproj/db.sqlite3
|
||||
testproj/staticfiles
|
||||
.vscode/
|
||||
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
|
||||
Generated
+2
-2
@@ -4,7 +4,7 @@
|
||||
<facet type="django" name="Django">
|
||||
<configuration>
|
||||
<option name="rootFolder" value="$MODULE_DIR$/testproj" />
|
||||
<option name="settingsModule" value="testproj/settings.py" />
|
||||
<option name="settingsModule" value="testproj/settings/local.py" />
|
||||
<option name="manageScript" value="manage.py" />
|
||||
<option name="environment" value="<map/>" />
|
||||
<option name="doNotUseTestRunner" value="false" />
|
||||
@@ -32,4 +32,4 @@
|
||||
<option name="projectConfiguration" value="py.test" />
|
||||
<option name="PROJECT_TEST_RUNNER" value="py.test" />
|
||||
</component>
|
||||
</module>
|
||||
</module>
|
||||
|
||||
+42
-34
@@ -1,56 +1,31 @@
|
||||
language: python
|
||||
cache: pip
|
||||
|
||||
python:
|
||||
- '2.7'
|
||||
- '3.4'
|
||||
- '3.5'
|
||||
- '3.6'
|
||||
- '3.7-dev'
|
||||
|
||||
env:
|
||||
- DRF=3.7
|
||||
|
||||
install:
|
||||
- pip install -r requirements/ci.txt
|
||||
|
||||
before_script:
|
||||
- coverage erase
|
||||
|
||||
script:
|
||||
- tox
|
||||
|
||||
after_success:
|
||||
- codecov
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- /^release\/.*$/
|
||||
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: always
|
||||
on_failure: always
|
||||
|
||||
jobs:
|
||||
fast_finish: true
|
||||
|
||||
include:
|
||||
- stage: test
|
||||
python: '3.6'
|
||||
env: DRF=master
|
||||
-
|
||||
python: '3.5'
|
||||
env: TOXENV=docs
|
||||
-
|
||||
python: '2.7'
|
||||
env: TOXENV=flake8
|
||||
-
|
||||
python: '3.6'
|
||||
env: DRF=master
|
||||
env: TOXENV=lint
|
||||
|
||||
- stage: publish
|
||||
python: '3.6'
|
||||
script: skip
|
||||
env:
|
||||
env: PYPI_DEPLOY=true
|
||||
deploy: &pypi
|
||||
provider: pypi
|
||||
user: cvijdea
|
||||
@@ -58,14 +33,47 @@ jobs:
|
||||
secure: 54DvknusZ7uHlo9IJxgbNDVKYrwaScyuOZyAGZPb/PTUj8WroQZtp1bFOrAtzfcM4ctIIoLWVzmSwrxypmU4hNif2ZvJ8Vo2PnVh9G6wQ2fD2FN+kFBYczBNrzW5xhjJ53OiTYy/zzHgzxC/sp+hB4sibWl0v69PGU5v6oyBltOWZLXYpqMA6fINt62XDVwuNHVKAo1T/yoeJMQKeCKYAx8QOtve9/qcl5Td/OOM6z42hX5+q3N7RgkCFLl0KopwaPwBaL1Z3Bn+aUhiIUdrRrdigY329QtNXoa/VRBNvUSAwbvecShmgl3c9HigL2ZWmtmHaXda6YCdqmbVfSHSEDsn4AwhZ3A9WblbRtuBwP79YKiE+4BLmgLlGGA4IrAKr3woe+078q/bGqBzmeDd+jt72hhibzD5B96zo4tSNksSxSJGwMYH988fBN/ppynrzRvO0sR/THwpb0r42era8tRd3ZVBefloVas/nQZZs4+zMYoO0fbaLDXdkfaxsF5/X6WkwTYjbI3tdapUT6lYXwi1eKUM1ZGsfKpuq0lFa3qxevYBKveWStQwGyJz1KhVUHbo3OrA3U6q9yoqpzhcZBhzGAPSgumi+EkBUj69cymlYkmqXVBn4VnWsdeFefNYE6Kvh/HJEDPDaWSNgfVLN9xWVqJqM7QiWA351W9dRZA=
|
||||
on:
|
||||
tags: true
|
||||
distributions: sdist
|
||||
distributions: "sdist bdist_wheel"
|
||||
|
||||
allow_failures:
|
||||
- env: TOXENV=flake8
|
||||
- env: TOXENV=lint
|
||||
- env: DRF=master
|
||||
- python: '3.7-dev'
|
||||
|
||||
fast_finish: true
|
||||
|
||||
install:
|
||||
- pip install -r requirements/ci.txt
|
||||
|
||||
before_script:
|
||||
- coverage erase
|
||||
- |
|
||||
[[ -z "$TOXENV" && -z "$PYPI_DEPLOY" ]] && REPORT_COVERAGE="yes" || REPORT_COVERAGE="no";
|
||||
echo "Reporting coverage: ${REPORT_COVERAGE}"
|
||||
- |
|
||||
[[ -z "$TOXENV" && ! -z "$DRF" && "$DRF" != "master" ]] && USE_DETOX="yes" || USE_DETOX="no";
|
||||
echo "Using detox: ${USE_DETOX}"
|
||||
|
||||
script:
|
||||
- 'if [[ "$USE_DETOX" == "yes" ]]; then detox; else tox; fi'
|
||||
|
||||
after_success:
|
||||
- coverage combine
|
||||
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then coverage report; fi'
|
||||
- 'if [[ "$REPORT_COVERAGE" == "yes" ]]; then codecov; fi'
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- /^release\/.*$/
|
||||
- /^v?\d+\.\d+(\.\d+)?(-?\S+)?$/
|
||||
|
||||
stages:
|
||||
- test
|
||||
- name: publish
|
||||
if: tag IS present
|
||||
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: always
|
||||
on_failure: always
|
||||
|
||||
+23
-1
@@ -36,7 +36,7 @@ You want to contribute some code? Great! Here are a few steps to get you started
|
||||
$ virtualenv venv
|
||||
$ source venv/bin/activate
|
||||
(venv) $ pip install -e .[validation]
|
||||
(venv) $ pip install -rrequirements/dev.txt -rrequirements/test.txt "Django>=1.11.7"
|
||||
(venv) $ pip install -rrequirements/dev.txt "Django>=1.11.7"
|
||||
|
||||
#. **Make your changes and check them against the test project**
|
||||
|
||||
@@ -95,3 +95,25 @@ You want to contribute some code? Great! Here are a few steps to get you started
|
||||
#. **Your code must pass all the required travis jobs before it is merged**
|
||||
|
||||
As of now, this consists of running on Python 2.7, 3.4, 3.5 and 3.6, and building the docs succesfully.
|
||||
|
||||
******************
|
||||
Maintainer's notes
|
||||
******************
|
||||
|
||||
Release checklist
|
||||
=================
|
||||
|
||||
* update ``docs/changelog.rst`` with changes since the last tagged version
|
||||
* commit & tag the release - ``git tag x.x.x -m "Release version x.x.x"``
|
||||
* push using ``git push --follow-tags``
|
||||
* verify that `Travis`_ has built the tag and succesfully published the release to `PyPI`_
|
||||
* publish release notes `on GitHub`_
|
||||
* start the `ReadTheDocs build`_ if it has not already started
|
||||
* deploy the live demo `on Heroku`_
|
||||
|
||||
|
||||
.. _Travis: https://travis-ci.org/axnsan12/drf-yasg/builds
|
||||
.. _PyPI: https://pypi.org/project/drf-yasg/
|
||||
.. _on GitHub: https://github.com/axnsan12/drf-yasg/releases
|
||||
.. _ReadTheDocs build: https://readthedocs.org/projects/drf-yasg/builds/
|
||||
.. _on Heroku: https://dashboard.heroku.com/pipelines/412d1cae-6a95-4f5e-810b-94869133f36a
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
release: python testproj/manage.py migrate && python testproj/manage.py shell -c "import createsuperuser"
|
||||
web: gunicorn --chdir testproj testproj.wsgi --log-file -
|
||||
+33
-87
@@ -11,30 +11,39 @@ Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framewor
|
||||
|
||||
Compatible with
|
||||
|
||||
- **Django Rest Framework**: 3.7
|
||||
- **Django**: 1.11, 2.0
|
||||
- **Django Rest Framework**: 3.7.7
|
||||
- **Django**: 1.11.x, 2.0.x
|
||||
- **Python**: 2.7, 3.4, 3.5, 3.6
|
||||
|
||||
**Source**: https://github.com/axnsan12/drf-yasg/
|
||||
Resources:
|
||||
|
||||
**Documentation**: https://drf-yasg.readthedocs.io/en/latest/
|
||||
* **Source**: https://github.com/axnsan12/drf-yasg/
|
||||
* **Documentation**: https://drf-yasg.readthedocs.io/
|
||||
* **Changelog**: https://drf-yasg.readthedocs.io/en/stable/changelog.html
|
||||
* **Live demo**: https://drf-yasg-demo.herokuapp.com/
|
||||
|
||||
.. image:: https://www.herokucdn.com/deploy/button.svg
|
||||
:target: https://heroku.com/deploy?template=https://github.com/axnsan12/drf-yasg
|
||||
:alt: heroku deploy button
|
||||
|
||||
********
|
||||
Features
|
||||
********
|
||||
|
||||
- full support for nested Serializers and Schemas
|
||||
- response schemas and descriptions
|
||||
- model definitions compatible with codegen tools
|
||||
- customization hooks at all points in the spec generation process
|
||||
- JSON and YAML format for spec
|
||||
- bundles latest version of
|
||||
`swagger-ui <https://github.com/swagger-api/swagger-ui>`_ and
|
||||
`redoc <https://github.com/Rebilly/ReDoc>`_ for viewing the generated documentation
|
||||
- schema view is cacheable out of the box
|
||||
- generated Swagger schema can be automatically validated by
|
||||
`swagger-spec-validator <https://github.com/Yelp/swagger_spec_validator>`_ or
|
||||
`flex <https://github.com/pipermerriam/flex>`_
|
||||
- full support for nested Serializers and Schemas
|
||||
- response schemas and descriptions
|
||||
- model definitions compatible with codegen tools
|
||||
- customization hooks at all points in the spec generation process
|
||||
- JSON and YAML format for spec
|
||||
- bundles latest version of
|
||||
`swagger-ui <https://github.com/swagger-api/swagger-ui>`_ and
|
||||
`redoc <https://github.com/Rebilly/ReDoc>`_ for viewing the generated documentation
|
||||
- schema view is cacheable out of the box
|
||||
- generated Swagger schema can be automatically validated by
|
||||
`swagger-spec-validator <https://github.com/Yelp/swagger_spec_validator>`_ or
|
||||
`flex <https://github.com/pipermerriam/flex>`_
|
||||
- supports Django REST Framework API versioning with ``URLPathVersioning`` and ``NamespaceVersioning``; other DRF
|
||||
or custom versioning schemes are not currently supported
|
||||
|
||||
.. figure:: https://raw.githubusercontent.com/axnsan12/drf-yasg/1.0.2/screenshots/redoc-nested-response.png
|
||||
:width: 100%
|
||||
@@ -119,7 +128,7 @@ In ``urls.py``:
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
),
|
||||
validators=['ssv', 'flex'],
|
||||
validators=['flex', 'ssv'],
|
||||
public=True,
|
||||
permission_classes=(permissions.AllowAny,),
|
||||
)
|
||||
@@ -145,12 +154,13 @@ This exposes 4 cached, validated and publicly available endpoints:
|
||||
a. ``get_schema_view`` parameters
|
||||
---------------------------------
|
||||
|
||||
- ``info`` - Required. Swagger API Info object
|
||||
- ``info`` - Swagger API Info object; if omitted, defaults to ``DEFAULT_INFO``
|
||||
- ``url`` - API base url; if left blank will be deduced from the location the view is served at
|
||||
- ``patterns`` - passed to SchemaGenerator
|
||||
- ``urlconf`` - passed to SchemaGenerator
|
||||
- ``public`` - if False, includes only endpoints the current user has access to
|
||||
- ``validators`` - a list of validator names to apply on the generated schema; allowed values are ``flex``, ``ssv``
|
||||
- ``generator_class`` - schema generator class to use; should be a subclass of ``OpenAPISchemaGenerator``
|
||||
- ``authentication_classes`` - authentication classes for the schema view itself
|
||||
- ``permission_classes`` - permission classes for the schema view itself
|
||||
|
||||
@@ -166,81 +176,17 @@ b. ``SchemaView`` options
|
||||
but with optional caching
|
||||
- you can, of course, call :python:`as_view` as usual
|
||||
|
||||
All of the first 3 methods take two optional arguments,
|
||||
``cache_timeout`` and ``cache_kwargs``; if present, these are passed on
|
||||
to Django’s :python:`cached_page` decorator in order to enable caching on the
|
||||
resulting view. See `3. Caching`_.
|
||||
All of the first 3 methods take two optional arguments, ``cache_timeout`` and ``cache_kwargs``; if present,
|
||||
these are passed on to Django’s :python:`cached_page` decorator in order to enable caching on the resulting view.
|
||||
See `3. Caching`_.
|
||||
|
||||
----------------------------------------------
|
||||
c. ``SWAGGER_SETTINGS`` and ``REDOC_SETTINGS``
|
||||
----------------------------------------------
|
||||
|
||||
Additionally, you can include some more settings in your ``settings.py`` file.
|
||||
The possible settings and their default values are as follows:
|
||||
See https://drf-yasg.readthedocs.io/en/stable/settings.html for details.
|
||||
|
||||
.. code:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
# default inspector classes, see advanced documentation
|
||||
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.inspectors.SwaggerAutoSchema',
|
||||
'DEFAULT_FIELD_INSPECTORS': [
|
||||
'drf_yasg.inspectors.CamelCaseJSONFilter',
|
||||
'drf_yasg.inspectors.ReferencingSerializerInspector',
|
||||
'drf_yasg.inspectors.RelatedFieldInspector',
|
||||
'drf_yasg.inspectors.ChoiceFieldInspector',
|
||||
'drf_yasg.inspectors.FileFieldInspector',
|
||||
'drf_yasg.inspectors.DictFieldInspector',
|
||||
'drf_yasg.inspectors.SimpleFieldInspector',
|
||||
'drf_yasg.inspectors.StringDefaultFieldInspector',
|
||||
],
|
||||
'DEFAULT_FILTER_INSPECTORS': [
|
||||
'drf_yasg.inspectors.CoreAPICompatInspector',
|
||||
],
|
||||
'DEFAULT_PAGINATOR_INSPECTORS': [
|
||||
'drf_yasg.inspectors.DjangoRestResponsePagination',
|
||||
'drf_yasg.inspectors.CoreAPICompatInspector',
|
||||
],
|
||||
|
||||
# default api Info if none is otherwise given; should be an import string to an openapi.Info object
|
||||
'DEFAULT_INFO': None,
|
||||
# default API url if none is otherwise given
|
||||
'DEFAULT_API_URL': '',
|
||||
|
||||
'USE_SESSION_AUTH': True, # add Django Login and Django Logout buttons, CSRF token to swagger UI page
|
||||
'LOGIN_URL': getattr(django.conf.settings, 'LOGIN_URL', None), # URL for the login button
|
||||
'LOGOUT_URL': getattr(django.conf.settings, 'LOGOUT_URL', None), # URL for the logout button
|
||||
|
||||
# Swagger security definitions to include in the schema;
|
||||
# see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-definitions-object
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'basic': {
|
||||
'type': 'basic'
|
||||
}
|
||||
},
|
||||
|
||||
# url to an external Swagger validation service; defaults to 'http://online.swagger.io/validator/'
|
||||
# set to None to disable the schema validation badge in the UI
|
||||
'VALIDATOR_URL': '',
|
||||
|
||||
# swagger-ui configuration settings, see https://github.com/swagger-api/swagger-ui/blob/112bca906553a937ac67adc2e500bdeed96d067b/docs/usage/configuration.md#parameters
|
||||
'OPERATIONS_SORTER': None,
|
||||
'TAGS_SORTER': None,
|
||||
'DOC_EXPANSION': 'list',
|
||||
'DEEP_LINKING': False,
|
||||
'SHOW_EXTENSIONS': True,
|
||||
'DEFAULT_MODEL_RENDERING': 'model',
|
||||
'DEFAULT_MODEL_DEPTH': 3,
|
||||
}
|
||||
|
||||
.. code:: python
|
||||
|
||||
REDOC_SETTINGS = {
|
||||
# ReDoc UI configuration settings, see https://github.com/Rebilly/ReDoc#redoc-tag-attributes
|
||||
'LAZY_RENDERING': True,
|
||||
'HIDE_HOSTNAME': False,
|
||||
'EXPAND_RESPONSES': 'all',
|
||||
'PATH_IN_MIDDLE': False,
|
||||
}
|
||||
|
||||
3. Caching
|
||||
==========
|
||||
@@ -260,7 +206,7 @@ caching the schema view in-memory, with some sane defaults:
|
||||
|
||||
Given the numerous methods to manually customzie the generated schema, it makes sense to validate the result to ensure
|
||||
it still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swagger
|
||||
libraries, and can be activated by passing :python:`validators=['ssv', 'flex']` to ``get_schema_view``; if the generated
|
||||
libraries, and can be activated by passing :python:`validators=['flex', 'ssv']` to ``get_schema_view``; if the generated
|
||||
schema is not valid, a :python:`SwaggerValidationError` is raised by the handling codec.
|
||||
|
||||
**Warning:** This internal validation can slow down your server.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "drf-yasg Demo app",
|
||||
"description": "A demonstrative app using https://github.com/axnsan12/drf-yasg",
|
||||
"repository": "https://github.com/axnsan12/drf-yasg",
|
||||
"logo": "https://swaggerhub.com/wp-content/uploads/2017/10/Swagger-Icon.svg",
|
||||
"keywords": [
|
||||
"django",
|
||||
"django-rest-framework",
|
||||
"swagger",
|
||||
"openapi"
|
||||
],
|
||||
"env": {
|
||||
"DJANGO_SETTINGS_MODULE": "testproj.settings.heroku",
|
||||
"DJANGO_SECRET_KEY": "m76=^#=z7xv5^(o%4dv9w7+1_c)y2m6)1ogjx%s@9$1^nupry="
|
||||
},
|
||||
"success_url": "/"
|
||||
}
|
||||
@@ -2,6 +2,39 @@
|
||||
Changelog
|
||||
#########
|
||||
|
||||
*********
|
||||
**1.3.0**
|
||||
*********
|
||||
|
||||
- **ADDED:** security requirements are now correctly set and can be customized; this should fix
|
||||
problems related to authentication in ``swagger-ui`` Try it out! (:issue:`50`, :pr:`54`)
|
||||
- **IMPROVED:** updated ``swagger-ui`` to version 3.9.2
|
||||
- **IMPROVED:** updated ``ReDoc`` to version 1.20.0
|
||||
- **FIXED:** fixed an exception caused by a warning in get_path_from_regex (:pr:`49`, thanks to :ghuser:`blueyed`)
|
||||
|
||||
*********
|
||||
**1.2.2**
|
||||
*********
|
||||
|
||||
- **FIXED:** djangorestframework>=3.7.7 is now required because of breaking changes
|
||||
(:issue:`44`, :pr:`45`, thanks to :ghuser:`h-hirokawa`)
|
||||
|
||||
*********
|
||||
**1.2.1**
|
||||
*********
|
||||
|
||||
- Fixed deployment issues
|
||||
|
||||
*********
|
||||
**1.2.0**
|
||||
*********
|
||||
|
||||
- **ADDED:** ``basePath`` is now generated by taking into account the ``SCRIPT_NAME`` variable and the
|
||||
longest common prefix of API urls (:issue:`37`, :pr:`42`)
|
||||
- **IMPROVED:** removed inline scripts and styles from bundled HTML templates to increase CSP compatibility
|
||||
- **IMPROVED:** improved validation errors and added more assertion sanity checks (:issue:`37`, :issue:`40`)
|
||||
- **IMPROVED:** improved handling of NamespaceVersioning by excluding endpoints of differing versions
|
||||
(i.e. when accesing the schema view for v1, v2 endpoints will not be included in swagger)
|
||||
|
||||
*********
|
||||
**1.1.3**
|
||||
|
||||
+1
-1
@@ -205,7 +205,7 @@ sys.path.insert(0, os.path.abspath('../src'))
|
||||
|
||||
# activate the Django testproj to be able to succesfully import drf_yasg
|
||||
sys.path.insert(0, os.path.abspath('../testproj'))
|
||||
os.putenv('DJANGO_SETTINGS_MODULE', 'testproj.settings')
|
||||
os.putenv('DJANGO_SETTINGS_MODULE', 'testproj.settings.local')
|
||||
|
||||
from django.conf import settings # noqa: E402
|
||||
|
||||
|
||||
@@ -9,126 +9,6 @@ Custom schema generation
|
||||
If the default spec generation does not quite match what you were hoping to achieve, ``drf-yasg`` provides some
|
||||
custom behavior hooks by default.
|
||||
|
||||
*********************
|
||||
Swagger spec overview
|
||||
*********************
|
||||
|
||||
This library generates OpenAPI 2.0 documents. The authoritative specification for this document's structure will always
|
||||
be the official documentation over at `swagger.io <https://swagger.io/>`__ and the `OpenAPI 2.0 specification
|
||||
page <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md>`__.
|
||||
|
||||
Beause the above specifications are a bit heavy and convoluted, here is a general overview of how the specification
|
||||
is structured, starting from the root ``Swagger`` object.
|
||||
|
||||
* :class:`.Swagger` object
|
||||
+ ``info``, ``schemes``, ``securityDefinitions`` and other informative attributes
|
||||
+ ``paths``: :class:`.Paths` object
|
||||
A list of all the paths in the API in the form of a mapping
|
||||
|
||||
- ``{path}``: :class:`.PathItem` - each :class:`.PathItem` has multiple operations keyed by method
|
||||
* ``{http_method}``: :class:`.Operation`
|
||||
Each operation is thus uniquely identified by its ``(path, http_method)`` combination,
|
||||
e.g. ``GET /articles/``, ``POST /articles/``, etc.
|
||||
* ``parameters``: [:class:`.Parameter`] - and a list of path parameters
|
||||
+ ``definitions``: named Models
|
||||
A list of all the named models in the API in the form of a mapping
|
||||
|
||||
- ``{ModelName}``: :class:`.Schema`
|
||||
|
||||
* :class:`.Operation` contains the following information about each operation:
|
||||
+ ``parameters``: [:class:`.Parameter`]
|
||||
A list of all the *query*, *header* and *form* parameters accepted by the operation.
|
||||
|
||||
- there can also be **at most one** body parameter whose structure is represented by a
|
||||
:class:`.Schema` or a reference to one (:class:`.SchemaRef`)
|
||||
+ ``responses``: :class:`.Responses`
|
||||
A list of all the possible responses the operation is expected to return. Each response can optionally have a
|
||||
:class:`.Schema` which describes the structure of its body.
|
||||
|
||||
- ``{status_code}``: :class:`.Response` - mapping of status code to response definition
|
||||
|
||||
+ ``operationId`` - should be unique across all operations
|
||||
+ ``tags`` - used to group operations in the listing
|
||||
|
||||
It is interesting to note the main differences between :class:`.Parameter` and :class:`.Schema` objects:
|
||||
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| :class:`.Schema` | :class:`.Parameter` |
|
||||
+==========================================================+===========================================================+
|
||||
| Can nest other Schemas | Cannot nest other Parameters |br| |
|
||||
| | Can only nest a Schema if the parameter is ``in: body`` |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot describe file uploads |br| | Can describe file uploads via ``type`` = ``file``, |br| |
|
||||
| - ``file`` is not permitted as a value for ``type`` | but only as part of a form :class:`.Operation` [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can be used in :class:`.Response`\ s | Cannot be used in :class:`.Response`\ s |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot be used in form :class:`.Operation`\ s [#formop]_ | Can be used in form :class:`.Operation`\ s [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can only describe request or response bodies | Can describe ``query``, ``form``, ``header`` or ``path`` |
|
||||
| | parameters |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
|
||||
.. [#formop] a form Operation is an :class:`.Operation` that consumes ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` content
|
||||
|
||||
* a form Operation cannot have ``body`` parameters
|
||||
* a non-form operation cannot have ``form`` parameters
|
||||
|
||||
****************
|
||||
Default behavior
|
||||
****************
|
||||
|
||||
This section describes where information is sourced from when using the default generation process.
|
||||
|
||||
* :class:`.Paths` are generated by exploring the patterns registered in your default ``urlconf``, or the ``patterns``
|
||||
and ``urlconf`` you specified when constructing :class:`.OpenAPISchemaGenerator`; only views inheriting from Django
|
||||
Rest Framework's ``APIView`` are looked at, all other views are ignored
|
||||
* ``path`` :class:`.Parameter`\ s are generated by looking in the URL pattern for any template parameters; attempts are
|
||||
made to guess their type from the views ``queryset`` and ``lookup_field``, if applicable. You can override path
|
||||
parameters via ``manual_parameters`` in :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
* ``query`` :class:`.Parameter`\ s - i.e. parameters specified in the URL as ``/path/?query1=value&query2=value`` -
|
||||
are generated from your view's ``filter_backends`` and ``paginator``, if any are declared. Additional parameters can
|
||||
be specified via the ``query_serializer`` and ``manual_parameters`` arguments of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`
|
||||
* The request body is only generated for the HTTP ``POST``, ``PUT`` and ``PATCH`` methods, and is sourced from the
|
||||
view's ``serializer_class``. You can also override the request body using the ``request_body`` argument of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
|
||||
- if the view represents a form request (that is, all its parsers are of the ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` media types), the request body will be output as ``form``
|
||||
:class:`.Parameter`\ s
|
||||
- if it is not a form request, the request body will be output as a single ``body`` :class:`.Parameter` wrapped
|
||||
around a :class:`.Schema`
|
||||
|
||||
* ``header`` :class:`.Parameter`\ s are supported by the OpenAPI specification but are never generated by this library;
|
||||
you can still add them using ``manual_parameters``.
|
||||
* :class:`.Responses` are generated as follows:
|
||||
|
||||
+ if ``responses`` is provided to :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>` and contains at least
|
||||
one success status code (i.e. any `2xx` status code), no automatic response is generated and the given response
|
||||
is used as described in the :func:`@swagger_auto_schema documentation <.swagger_auto_schema>`
|
||||
+ otherwise, an attempt is made to generate a default response:
|
||||
|
||||
- the success status code is assumed to be ``204` for ``DELETE`` requests, ``201`` for ``POST`` requests, and
|
||||
``200`` for all other request methods
|
||||
- if the view has a request body, the same ``Serializer`` or :class:`.Schema` as in the request body is used
|
||||
in generating the :class:`.Response` schema; this is inline with the default ``GenericAPIView`` and
|
||||
``GenericViewSet`` behavior
|
||||
- if the view has no request body, its ``serializer_class`` is used to generate the :class:`.Response` schema
|
||||
- if the view is a list view (as defined by :func:`.is_list_view`), the response schema is wrapped in an array
|
||||
- if the view is also paginated, the response schema is then wrapped in the appropriate paging response structure
|
||||
- the description of the response is left blank
|
||||
|
||||
* :class:`.Response` headers are supported by the OpenAPI specification but not currently supported by this library;
|
||||
you can still add them manually by providing an `appropriately structured dictionary
|
||||
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headersObject>`_
|
||||
to the ``headers`` property of a :class:`.Response` object
|
||||
* *descriptions* for :class:`.Operation`\ s, :class:`.Parameter`\ s and :class:`.Schema`\ s are picked up from
|
||||
docstrings and ``help_text`` attributes in the same manner as the `default DRF SchemaGenerator
|
||||
<http://www.django-rest-framework.org/api-guide/schemas/#schemas-as-documentation>`_
|
||||
|
||||
|
||||
.. _custom-spec-swagger-auto-schema:
|
||||
|
||||
**************************************
|
||||
|
||||
@@ -12,6 +12,8 @@ drf-yasg
|
||||
|
||||
readme.rst
|
||||
rendering.rst
|
||||
openapi.rst
|
||||
security.rst
|
||||
custom_spec.rst
|
||||
custom_ui.rst
|
||||
settings.rst
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
.. |br| raw:: html
|
||||
|
||||
<br />
|
||||
|
||||
**********************
|
||||
Functional overview
|
||||
**********************
|
||||
|
||||
|
||||
------------------------------
|
||||
OpenAPI specification overview
|
||||
------------------------------
|
||||
|
||||
This library generates OpenAPI 2.0 documents. The authoritative specification for this document's structure will always
|
||||
be the official documentation over at `swagger.io <https://swagger.io/>`__ and the `OpenAPI 2.0 specification
|
||||
page <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md>`__.
|
||||
|
||||
Beause the above specifications are a bit heavy and convoluted, here is a general overview of how the specification
|
||||
is structured, starting from the root ``Swagger`` object.
|
||||
|
||||
* :class:`.Swagger` object
|
||||
+ ``info``, ``schemes``, ``securityDefinitions`` and other informative attributes
|
||||
+ ``paths``: :class:`.Paths` object
|
||||
A list of all the paths in the API in the form of a mapping
|
||||
|
||||
- ``{path}``: :class:`.PathItem` - each :class:`.PathItem` has multiple operations keyed by method
|
||||
* ``{http_method}``: :class:`.Operation`
|
||||
Each operation is thus uniquely identified by its ``(path, http_method)`` combination,
|
||||
e.g. ``GET /articles/``, ``POST /articles/``, etc.
|
||||
* ``parameters``: [:class:`.Parameter`] - and a list of path parameters
|
||||
+ ``definitions``: named Models
|
||||
A list of all the named models in the API in the form of a mapping
|
||||
|
||||
- ``{ModelName}``: :class:`.Schema`
|
||||
|
||||
* :class:`.Operation` contains the following information about each operation:
|
||||
+ ``parameters``: [:class:`.Parameter`]
|
||||
A list of all the *query*, *header* and *form* parameters accepted by the operation.
|
||||
|
||||
- there can also be **at most one** body parameter whose structure is represented by a
|
||||
:class:`.Schema` or a reference to one (:class:`.SchemaRef`)
|
||||
+ ``responses``: :class:`.Responses`
|
||||
A list of all the possible responses the operation is expected to return. Each response can optionally have a
|
||||
:class:`.Schema` which describes the structure of its body.
|
||||
|
||||
- ``{status_code}``: :class:`.Response` - mapping of status code to response definition
|
||||
|
||||
+ ``operationId`` - should be unique across all operations
|
||||
+ ``tags`` - used to group operations in the listing
|
||||
|
||||
It is interesting to note the main differences between :class:`.Parameter` and :class:`.Schema` objects:
|
||||
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| :class:`.Schema` | :class:`.Parameter` |
|
||||
+==========================================================+===========================================================+
|
||||
| Can nest other Schemas | Cannot nest other Parameters |br| |
|
||||
| | Can only nest a Schema if the parameter is ``in: body`` |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot describe file uploads |br| | Can describe file uploads via ``type`` = ``file``, |br| |
|
||||
| - ``file`` is not permitted as a value for ``type`` | but only as part of a form :class:`.Operation` [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can be used in :class:`.Response`\ s | Cannot be used in :class:`.Response`\ s |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Cannot be used in form :class:`.Operation`\ s [#formop]_ | Can be used in form :class:`.Operation`\ s [#formop]_ |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
| Can only describe request or response bodies | Can describe ``query``, ``form``, ``header`` or ``path`` |
|
||||
| | parameters |
|
||||
+----------------------------------------------------------+-----------------------------------------------------------+
|
||||
|
||||
.. [#formop] a form Operation is an :class:`.Operation` that consumes ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` content
|
||||
|
||||
* a form Operation cannot have ``body`` parameters
|
||||
* a non-form operation cannot have ``form`` parameters
|
||||
|
||||
----------------
|
||||
Default behavior
|
||||
----------------
|
||||
|
||||
This section describes where information is sourced from when using the default generation process.
|
||||
|
||||
* :class:`.Paths` are generated by exploring the patterns registered in your default ``urlconf``, or the ``patterns``
|
||||
and ``urlconf`` you specified when constructing :class:`.OpenAPISchemaGenerator`; only views inheriting from Django
|
||||
Rest Framework's ``APIView`` are looked at, all other views are ignored
|
||||
* ``path`` :class:`.Parameter`\ s are generated by looking in the URL pattern for any template parameters; attempts are
|
||||
made to guess their type from the views ``queryset`` and ``lookup_field``, if applicable. You can override path
|
||||
parameters via ``manual_parameters`` in :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
* ``query`` :class:`.Parameter`\ s - i.e. parameters specified in the URL as ``/path/?query1=value&query2=value`` -
|
||||
are generated from your view's ``filter_backends`` and ``paginator``, if any are declared. Additional parameters can
|
||||
be specified via the ``query_serializer`` and ``manual_parameters`` arguments of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`
|
||||
* The request body is only generated for the HTTP ``POST``, ``PUT`` and ``PATCH`` methods, and is sourced from the
|
||||
view's ``serializer_class``. You can also override the request body using the ``request_body`` argument of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
|
||||
- if the view represents a form request (that is, all its parsers are of the ``multipart/form-data`` or
|
||||
``application/x-www-form-urlencoded`` media types), the request body will be output as ``form``
|
||||
:class:`.Parameter`\ s
|
||||
- if it is not a form request, the request body will be output as a single ``body`` :class:`.Parameter` wrapped
|
||||
around a :class:`.Schema`
|
||||
|
||||
* ``header`` :class:`.Parameter`\ s are supported by the OpenAPI specification but are never generated by this library;
|
||||
you can still add them using ``manual_parameters``.
|
||||
* :class:`.Responses` are generated as follows:
|
||||
|
||||
+ if ``responses`` is provided to :ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>` and contains at least
|
||||
one success status code (i.e. any `2xx` status code), no automatic response is generated and the given response
|
||||
is used as described in the :func:`@swagger_auto_schema documentation <.swagger_auto_schema>`
|
||||
+ otherwise, an attempt is made to generate a default response:
|
||||
|
||||
- the success status code is assumed to be ``204` for ``DELETE`` requests, ``201`` for ``POST`` requests, and
|
||||
``200`` for all other request methods
|
||||
- if the view has a request body, the same ``Serializer`` or :class:`.Schema` as in the request body is used
|
||||
in generating the :class:`.Response` schema; this is inline with the default ``GenericAPIView`` and
|
||||
``GenericViewSet`` behavior
|
||||
- if the view has no request body, its ``serializer_class`` is used to generate the :class:`.Response` schema
|
||||
- if the view is a list view (as defined by :func:`.is_list_view`), the response schema is wrapped in an array
|
||||
- if the view is also paginated, the response schema is then wrapped in the appropriate paging response structure
|
||||
- the description of the response is left blank
|
||||
|
||||
* :class:`.Response` headers are supported by the OpenAPI specification but not currently supported by this library;
|
||||
you can still add them manually by providing an `appropriately structured dictionary
|
||||
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headersObject>`_
|
||||
to the ``headers`` property of a :class:`.Response` object
|
||||
* *descriptions* for :class:`.Operation`\ s, :class:`.Parameter`\ s and :class:`.Schema`\ s are picked up from
|
||||
docstrings and ``help_text`` attributes in the same manner as the `default DRF SchemaGenerator
|
||||
<http://www.django-rest-framework.org/api-guide/schemas/#schemas-as-documentation>`_
|
||||
* .. _custom-spec-base-url:
|
||||
|
||||
The base URL for the API consists of three values - the ``host``, ``schemes`` and ``basePath`` attributes
|
||||
* The host name and scheme are determined, in descending order of priority:
|
||||
|
||||
+ from the ``url`` argument passed to :func:`.get_schema_view` (more specifically, to the underlying
|
||||
:class:`.OpenAPISchemaGenerator`)
|
||||
+ from the :ref:`DEFAULT_API_URL setting <default-swagger-settings>`
|
||||
+ inferred from the request made to the schema endpoint
|
||||
|
||||
For example, an url of ``https://www.example.com:8080/some/path`` will populate the ``host`` and ``schemes``
|
||||
attributes with ``www.example.com:8080`` and ``['https']``, respectively. The path component will be ignored.
|
||||
* The base path is determined as the concatenation of two variables:
|
||||
|
||||
#. the `SCRIPT_NAME`_ wsgi environment variable; this is set, for example, when serving the site from a
|
||||
sub-path using web server url rewriting
|
||||
|
||||
.. Tip::
|
||||
|
||||
The Django `FORCE_SCRIPT_NAME`_ setting can be used to override the `SCRIPT_NAME`_ or set it when it's
|
||||
missing from the environment.
|
||||
|
||||
#. the longest common path prefix of all the urls in your API - see :meth:`.determine_path_prefix`
|
||||
|
||||
* When using API versioning with ``NamespaceVersioning`` or ``URLPathVersioning``, versioned endpoints that do not
|
||||
match the version used to access the ``SchemaView`` will be excluded from the endpoint list - for example,
|
||||
``/api/v1.0/endpoint`` will be shown when viewing ``/api/v1.0/swagger/``, while ``/api/v2.0/endpoint`` will not
|
||||
|
||||
Other versioning schemes are not presently supported.
|
||||
|
||||
|
||||
.. versionadded:: 1.2
|
||||
Base path and versioning support.
|
||||
|
||||
.. _SCRIPT_NAME: https://www.python.org/dev/peps/pep-0333/#environ-variables
|
||||
.. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name
|
||||
+2
-2
@@ -66,7 +66,7 @@ See the command help for more advanced options:
|
||||
|
||||
In ``settings.py``:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'DEFAULT_INFO': 'import.path.to.urls.api_info',
|
||||
@@ -74,7 +74,7 @@ See the command help for more advanced options:
|
||||
|
||||
In ``urls.py``:
|
||||
|
||||
.. code:: python
|
||||
.. code-block:: python
|
||||
|
||||
api_info = openapi.Info(
|
||||
title="Snippets API",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
*********************************
|
||||
Describing authentication schemes
|
||||
*********************************
|
||||
|
||||
When using the `swagger-ui` frontend, it is possible to interact with the API described by your Swagger document.
|
||||
This interaction might require authentication, which you will have to describe in order to make `swagger-ui` work
|
||||
with it.
|
||||
|
||||
|
||||
--------------------
|
||||
Security definitions
|
||||
--------------------
|
||||
|
||||
The first step that you have to do is add a :ref:`SECURITY_DEFINITIONS <security-definitions-settings>` setting
|
||||
to declare all authentication schemes supported by your API.
|
||||
|
||||
For example, the definition for a simple API accepting HTTP basic auth and `Authorization` header API tokens would be:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'Basic': {
|
||||
'type': 'basic'
|
||||
},
|
||||
'Bearer': {
|
||||
'type': 'apiKey',
|
||||
'name': 'Authorization',
|
||||
'in': 'header'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
---------------------
|
||||
Security requirements
|
||||
---------------------
|
||||
|
||||
The second step is specifying, for each endpoint, which authentication mechanism can be used for interacting with it.
|
||||
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#security-requirement-object for details.
|
||||
|
||||
By default, a top-level `security` that accepts all the declared security definitions is generated.
|
||||
For the example above, that would be :code:`[{'Basic': []}, {'Bearer': []}]`. This can be overriden using the
|
||||
:ref:`SECURITY_REQUIREMENTS <security-definitions-settings>` setting.
|
||||
|
||||
Operation-level overrides can be added using the ``security`` parameter of
|
||||
:ref:`@swagger_auto_schema <custom-spec-swagger-auto-schema>`.
|
||||
|
||||
|
||||
+20
-3
@@ -107,10 +107,13 @@ management command, or if no ``info`` argument is passed to ``get_schema_view``.
|
||||
DEFAULT_API_URL
|
||||
---------------
|
||||
|
||||
A string representing the default API URL. This will be used to populate the ``host``, ``schemes`` and ``basePath``
|
||||
attributes of the Swagger document if no API URL is otherwise provided.
|
||||
A string representing the default API URL. This will be used to populate the ``host`` and ``schemes`` attributes
|
||||
of the Swagger document if no API URL is otherwise provided. The Django `FORCE_SCRIPT_NAME`_ setting can be used for
|
||||
providing an API mount point prefix.
|
||||
|
||||
**Default**: :python:`''`
|
||||
See also: :ref:`documentation on base URL construction <custom-spec-base-url>`
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
Authorization
|
||||
=============
|
||||
@@ -137,6 +140,9 @@ URL for the Django Logout action when using `USE_SESSION_AUTH`_.
|
||||
|
||||
**Default**: :python:`django.conf.settings.LOGOUT_URL`
|
||||
|
||||
.. _security-definitions-settings:
|
||||
|
||||
|
||||
SECURITY_DEFINITIONS
|
||||
--------------------
|
||||
|
||||
@@ -151,6 +157,14 @@ See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#sec
|
||||
'type': 'basic'
|
||||
}
|
||||
|
||||
SECURITY_REQUIREMENTS
|
||||
---------------------
|
||||
|
||||
Global security requirements. If :python:`None`, all schemes in ``SECURITY_DEFINITIONS`` are accepted. |br|
|
||||
See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject.
|
||||
|
||||
**Default**: :python:`None`
|
||||
|
||||
.. _swagger-ui-settings:
|
||||
|
||||
Swagger UI settings
|
||||
@@ -274,3 +288,6 @@ PATH_IN_MIDDLE
|
||||
|
||||
**Default**: :python:`False` |br|
|
||||
*Maps to attribute*: ``path-in-middle-panel``
|
||||
|
||||
|
||||
.. _FORCE_SCRIPT_NAME: https://docs.djangoproject.com/en/2.0/ref/settings/#force-script-name
|
||||
|
||||
Generated
+40
-40
@@ -38,9 +38,9 @@
|
||||
}
|
||||
},
|
||||
"commander": {
|
||||
"version": "2.12.2",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.12.2.tgz",
|
||||
"integrity": "sha512-BFnaq5ZOGcDN7FlrtBT4xxkgIToalIIxwjxLWVJ8bGTpe1LroqMiqQXdA7ygc7CRvaYS+9zfPGFnJqFSayx+AA==",
|
||||
"version": "2.13.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-2.13.0.tgz",
|
||||
"integrity": "sha512-MVuS359B+YzaWqjCL/c+22gfryv+mCBPHAv3zyVI2GN8EY6IRP8VwtasXn8jyyhvvq84R4ImN1OKRtcbIasjYA==",
|
||||
"optional": true
|
||||
},
|
||||
"core-js": {
|
||||
@@ -73,9 +73,9 @@
|
||||
"integrity": "sha1-8TyUAhQdoJ50rfTmN5jXkiBEOPI="
|
||||
},
|
||||
"es6-promise": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.1.1.tgz",
|
||||
"integrity": "sha512-OaU1hHjgJf+b0NzsxCg7NdIYERD6Hy/PEmFLTjw+b65scuisG3Kt4QoTvJ66BBkPZ581gr0kpoVzKnxniM8nng=="
|
||||
"version": "4.2.2",
|
||||
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.2.tgz",
|
||||
"integrity": "sha512-LSas5vsuA6Q4nEdf9wokY5/AJYXry98i0IzXsv49rYsgDGDNDPbqAYR1Pe23iFxygfbGZNR/5VrHXBCh2BhvUQ=="
|
||||
},
|
||||
"esprima": {
|
||||
"version": "4.0.0",
|
||||
@@ -145,9 +145,9 @@
|
||||
"requires": {
|
||||
"call-me-maybe": "1.0.1",
|
||||
"debug": "3.1.0",
|
||||
"es6-promise": "4.1.1",
|
||||
"es6-promise": "4.2.2",
|
||||
"js-yaml": "3.10.0",
|
||||
"ono": "4.0.2",
|
||||
"ono": "4.0.3",
|
||||
"z-schema": "3.19.0"
|
||||
}
|
||||
},
|
||||
@@ -166,15 +166,20 @@
|
||||
"resolved": "https://registry.npmjs.org/lunr/-/lunr-1.0.0.tgz",
|
||||
"integrity": "sha1-XJJ2ySyRrDWpJBtQGNRnI9kuL18="
|
||||
},
|
||||
"mark.js": {
|
||||
"version": "8.11.1",
|
||||
"resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz",
|
||||
"integrity": "sha1-GA8fnr74sOY45BZq1S24eb6y/8U="
|
||||
},
|
||||
"ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
|
||||
},
|
||||
"ono": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/ono/-/ono-4.0.2.tgz",
|
||||
"integrity": "sha512-EFXJFoeF+KkZW4lwmcPMKHp2ZU7o6CM+ccX2nPbEJKiJIdyqbIcS1v6pmNgeNJ6x4/vEYn0/8oz66qXSPnnmSQ==",
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/ono/-/ono-4.0.3.tgz",
|
||||
"integrity": "sha512-7QIxG4UB00H7CR7fhXC/U7VhB5DK9wsYLwaYBui1JmQoXtLkhIBn3fbuk6FgAP+ctWeBsWVTM+R/bThvUZN+ww==",
|
||||
"requires": {
|
||||
"format-util": "1.0.3"
|
||||
}
|
||||
@@ -190,9 +195,9 @@
|
||||
"integrity": "sha512-RNC5tX/JMRYR+qVdJTEAWnRxw0Yf9lvbO8lTuAOvgDODkiA8lveTSkvrNMhmaGKEyimJpJl+myb/syVS9YyPuw=="
|
||||
},
|
||||
"prismjs": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.9.0.tgz",
|
||||
"integrity": "sha1-+j4tntw8OIfB8fMJXUHx+bQgDw8=",
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.10.0.tgz",
|
||||
"integrity": "sha1-d+UYfCrmsyU/zDEwKc8l/lN3hyE=",
|
||||
"requires": {
|
||||
"clipboard": "1.7.1"
|
||||
}
|
||||
@@ -217,9 +222,9 @@
|
||||
}
|
||||
},
|
||||
"redoc": {
|
||||
"version": "1.19.3",
|
||||
"resolved": "https://registry.npmjs.org/redoc/-/redoc-1.19.3.tgz",
|
||||
"integrity": "sha1-DfPx+6S92G/+nGIAEzBxUjytVec=",
|
||||
"version": "1.20.0",
|
||||
"resolved": "https://registry.npmjs.org/redoc/-/redoc-1.20.0.tgz",
|
||||
"integrity": "sha1-1c16xoQKJ8/7RzvSiYAFUq+CHq8=",
|
||||
"requires": {
|
||||
"core-js": "2.5.3",
|
||||
"dropkickjs": "2.1.10",
|
||||
@@ -228,21 +233,16 @@
|
||||
"json-pointer": "0.6.0",
|
||||
"json-schema-ref-parser": "3.3.1",
|
||||
"lunr": "1.0.0",
|
||||
"mark.js": "github:julmot/mark.js#714c9523feca999267f1758da8cfd92d077105d0",
|
||||
"mark.js": "8.11.1",
|
||||
"openapi-sampler": "0.4.3",
|
||||
"perfect-scrollbar": "0.8.1",
|
||||
"prismjs": "1.9.0",
|
||||
"prismjs": "1.10.0",
|
||||
"remarkable": "1.7.1",
|
||||
"scrollparent": "2.0.1",
|
||||
"slugify": "1.2.6",
|
||||
"stream-http": "2.7.2",
|
||||
"slugify": "1.2.9",
|
||||
"stream-http": "2.8.0",
|
||||
"ts-helpers": "1.1.2",
|
||||
"zone.js": "0.8.18"
|
||||
},
|
||||
"dependencies": {
|
||||
"mark.js": {
|
||||
"version": "github:julmot/mark.js#714c9523feca999267f1758da8cfd92d077105d0"
|
||||
}
|
||||
"zone.js": "0.8.20"
|
||||
}
|
||||
},
|
||||
"remarkable": {
|
||||
@@ -282,9 +282,9 @@
|
||||
"optional": true
|
||||
},
|
||||
"slugify": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.2.6.tgz",
|
||||
"integrity": "sha512-796YAGnzEnLKQHAFf7H2q1nsjY/9qywSnF9ZkMUbs9he4aZaXO/zFUow0LZ95sBAiQjOX1EmGl23gTYaswiNaQ=="
|
||||
"version": "1.2.9",
|
||||
"resolved": "https://registry.npmjs.org/slugify/-/slugify-1.2.9.tgz",
|
||||
"integrity": "sha512-n0cdJ+kN3slJu8SbZXt/EHjljBqF6MxvMGSg/NPpBzoY7yyXoH38wp/ox20a1JaG1KgmdTN5Lf3aS9+xB2Y2aQ=="
|
||||
},
|
||||
"sprintf-js": {
|
||||
"version": "1.0.3",
|
||||
@@ -292,9 +292,9 @@
|
||||
"integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw="
|
||||
},
|
||||
"stream-http": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.7.2.tgz",
|
||||
"integrity": "sha512-c0yTD2rbQzXtSsFSVhtpvY/vS6u066PcXOX9kBB3mSO76RiUQzL340uJkGBWnlBg4/HZzqiUXtaVA7wcRcJgEw==",
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.0.tgz",
|
||||
"integrity": "sha512-sZOFxI/5xw058XIRHl4dU3dZ+TTOIGJR78Dvo0oEAejIt4ou27k+3ne1zYmCV+v7UucbxIFQuOgnkTVHh8YPnw==",
|
||||
"requires": {
|
||||
"builtin-status-codes": "3.0.0",
|
||||
"inherits": "2.0.3",
|
||||
@@ -312,9 +312,9 @@
|
||||
}
|
||||
},
|
||||
"swagger-ui-dist": {
|
||||
"version": "3.8.1",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.8.1.tgz",
|
||||
"integrity": "sha1-jzVrkwjZl3oJ1eQYGvdCAHPtzdk="
|
||||
"version": "3.9.2",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.9.2.tgz",
|
||||
"integrity": "sha1-XuK7G2IFPC3ydGnlVZDGX8AOidQ="
|
||||
},
|
||||
"tiny-emitter": {
|
||||
"version": "2.0.2",
|
||||
@@ -362,16 +362,16 @@
|
||||
"resolved": "https://registry.npmjs.org/z-schema/-/z-schema-3.19.0.tgz",
|
||||
"integrity": "sha512-V94f3ODuluBS4kQLLjNhwoMek0dyIXCsvNu/A17dAyJ6sMhT5KkJQwSn07R0naByLIXJWMDk+ruMfI/3G3hS4Q==",
|
||||
"requires": {
|
||||
"commander": "2.12.2",
|
||||
"commander": "2.13.0",
|
||||
"lodash.get": "4.4.2",
|
||||
"lodash.isequal": "4.5.0",
|
||||
"validator": "9.2.0"
|
||||
}
|
||||
},
|
||||
"zone.js": {
|
||||
"version": "0.8.18",
|
||||
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.8.18.tgz",
|
||||
"integrity": "sha512-knKOBQM0oea3/x9pdyDuDi7RhxDlJhOIkeixXSiTKWLgs4LpK37iBc+1HaHwzlciHUKT172CymJFKo8Xgh+44Q=="
|
||||
"version": "0.8.20",
|
||||
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.8.20.tgz",
|
||||
"integrity": "sha512-FXlA37ErSXCMy5RNBcGFgCI/Zivqzr0D19GuvDxhcYIJc7xkFp6c29DKyODJu0Zo+EMyur/WPPgcBh1EHjB9jA=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "drf-yasg",
|
||||
"dependencies": {
|
||||
"redoc": "^1.19.3",
|
||||
"swagger-ui-dist": "^3.8.1"
|
||||
"redoc": "^1.20.0",
|
||||
"swagger-ui-dist": "^3.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
.[validation]
|
||||
-r requirements/heroku.txt
|
||||
@@ -4,3 +4,9 @@ openapi_codec>=1.3.2
|
||||
ruamel.yaml>=0.15.34
|
||||
inflection>=0.3.1
|
||||
future>=0.16.0
|
||||
six>=1.11.0
|
||||
uritemplate>=3.0.0
|
||||
|
||||
djangorestframework>=3.7.7
|
||||
Django>=1.11.7,<2.0; python_version <= "2.7"
|
||||
Django>=1.11.7; python_version >= "3.4"
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
# requirements for CI test suite
|
||||
-r dev.txt
|
||||
# requirements for the CI test runner
|
||||
tox-travis>=0.10
|
||||
codecov>=2.0.9
|
||||
|
||||
-r tox.txt
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
# requirements for local development
|
||||
tox>=2.9.1
|
||||
# requirements for local development to be installed via pip install -r requirements/dev.txt
|
||||
-r tox.txt
|
||||
-r test.txt
|
||||
-r lint.txt
|
||||
|
||||
tox-battery>=0.5
|
||||
detox>=0.11
|
||||
|
||||
isort>=4.2
|
||||
flake8>=3.5.0
|
||||
flake8-isort>=2.3
|
||||
|
||||
-r setup.txt
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
Sphinx==1.6.5
|
||||
sphinx_rtd_theme==0.2.4
|
||||
Pillow==4.3.0
|
||||
readme_renderer==17.2
|
||||
# used by the 'docs' tox env for building the documentation
|
||||
Sphinx>=1.6.5
|
||||
sphinx_rtd_theme>=0.2.4
|
||||
Pillow>=4.3.0
|
||||
readme_renderer>=17.2
|
||||
|
||||
Django==2.0
|
||||
Django>=2.0,<2.1
|
||||
djangorestframework_camel_case>=0.2.0
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# requirements necessary when deploying the test project to heroku
|
||||
-r testproj.txt
|
||||
psycopg2>=2.7.3
|
||||
gunicorn>=19.7.1
|
||||
whitenoise>=3.3.1
|
||||
@@ -0,0 +1,4 @@
|
||||
# used by the 'lint' tox env for linting via flake8
|
||||
isort>=4.2
|
||||
flake8>=3.5.0
|
||||
flake8-isort>=2.3
|
||||
@@ -1,4 +1,4 @@
|
||||
# requirements for building the distributable package
|
||||
# needed to build the package setup_requires in setup.py
|
||||
|
||||
# do not unpin this (see setup.py)
|
||||
setuptools_scm==1.15.6
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# pytest runner + plugins
|
||||
# requirements for running the tests via pytest
|
||||
pytest>=2.9
|
||||
pytest-pythonpath>=0.7.1
|
||||
pytest-cov>=2.5.1
|
||||
pytest-xdist>=1.22.0
|
||||
# latest pip version of pytest-django is more than a year old and does not support Django 2.0
|
||||
git+https://github.com/pytest-dev/pytest-django.git@94cccb956435dd7a719606744ee7608397e1eafb
|
||||
datadiff==2.0.0
|
||||
|
||||
@@ -5,3 +5,5 @@ django-cors-headers>=2.1.0
|
||||
django-filter>=1.1.0,<2.0; python_version == "2.7"
|
||||
django-filter>=1.1.0; python_version >= "3.4"
|
||||
djangorestframework-camel-case>=0.2.0
|
||||
dj-database-url>=0.4.2
|
||||
user_agents>=1.1.0
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# requirements for building and running tox
|
||||
tox>=2.9.1
|
||||
detox>=0.11
|
||||
|
||||
-r setup.txt
|
||||
@@ -0,0 +1 @@
|
||||
python-3.6.4
|
||||
@@ -3,19 +3,21 @@
|
||||
import distutils.core
|
||||
import io
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import sys
|
||||
from setuptools import find_packages, setup
|
||||
|
||||
|
||||
def read_req(req_file):
|
||||
with open(os.path.join('requirements', req_file)) as req:
|
||||
return [line for line in req.readlines() if line and not line.isspace()]
|
||||
return [line.strip() for line in req.readlines() if line.strip() and not line.strip().startswith('#')]
|
||||
|
||||
|
||||
with io.open('README.rst', encoding='utf-8') as readme:
|
||||
description = readme.read()
|
||||
|
||||
requirements = ['djangorestframework>=3.7.0'] + read_req('base.txt')
|
||||
requirements = read_req('base.txt')
|
||||
requirements_setup = read_req('setup.txt')
|
||||
requirements_validation = read_req('validation.txt')
|
||||
|
||||
@@ -32,14 +34,14 @@ def _install_setup_requires(attrs):
|
||||
dist.fetch_build_eggs(dist.setup_requires)
|
||||
|
||||
|
||||
if 'sdist' in sys.argv:
|
||||
try:
|
||||
# try to install setuptools_scm before setuptools does it, otherwise our monkey patch below will come too early
|
||||
# (setuptools_scm adds find_files hooks into setuptools on install)
|
||||
_install_setup_requires({'setup_requires': requirements_setup})
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# try to install setuptools_scm before setuptools does it, otherwise our monkey patch below will come too early
|
||||
# (setuptools_scm adds find_files hooks into setuptools on install)
|
||||
_install_setup_requires({'setup_requires': requirements_setup})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if 'sdist' in sys.argv:
|
||||
try:
|
||||
# see https://github.com/pypa/setuptools_scm/issues/190, setuptools_scm includes ALL versioned files from
|
||||
# the git repo into the sdist by default, and there is no easy way to provide an opt-out;
|
||||
@@ -51,9 +53,22 @@ if 'sdist' in sys.argv:
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
# this is a workaround for being able to install the package from source without working from a git checkout
|
||||
# it is needed for building succesfully on Heroku
|
||||
from setuptools_scm import get_version
|
||||
|
||||
version = get_version()
|
||||
version_kwargs = {'use_scm_version': True}
|
||||
except LookupError:
|
||||
if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
|
||||
raise
|
||||
|
||||
rnd = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
|
||||
version_kwargs = {'version': '0.0.0.dummy+' + rnd}
|
||||
|
||||
setup(
|
||||
name='drf-yasg',
|
||||
use_scm_version=True,
|
||||
packages=find_packages('src'),
|
||||
package_dir={'': 'src'},
|
||||
include_package_data=True,
|
||||
@@ -70,6 +85,7 @@ setup(
|
||||
author_email='cristi@cvjd.me',
|
||||
keywords='drf django django-rest-framework schema swagger openapi codegen swagger-codegen '
|
||||
'documentation drf-yasg django-rest-swagger drf-openapi',
|
||||
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
|
||||
classifiers=[
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
@@ -89,4 +105,5 @@ setup(
|
||||
'Topic :: Documentation',
|
||||
'Topic :: Software Development :: Code Generators',
|
||||
],
|
||||
**version_kwargs
|
||||
)
|
||||
|
||||
@@ -23,7 +23,7 @@ SWAGGER_DEFAULTS = {
|
||||
],
|
||||
|
||||
'DEFAULT_INFO': None,
|
||||
'DEFAULT_API_URL': '',
|
||||
'DEFAULT_API_URL': None,
|
||||
|
||||
'USE_SESSION_AUTH': True,
|
||||
'SECURITY_DEFINITIONS': {
|
||||
@@ -31,6 +31,7 @@ SWAGGER_DEFAULTS = {
|
||||
'type': 'basic'
|
||||
}
|
||||
},
|
||||
'SECURITY_REQUIREMENTS': None,
|
||||
'LOGIN_URL': getattr(settings, 'LOGIN_URL', None),
|
||||
'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None),
|
||||
'VALIDATOR_URL': '',
|
||||
|
||||
+14
-9
@@ -8,26 +8,25 @@ from coreapi.compat import force_bytes
|
||||
from ruamel import yaml
|
||||
|
||||
from . import openapi
|
||||
from .app_settings import swagger_settings
|
||||
from .errors import SwaggerValidationError
|
||||
|
||||
|
||||
def _validate_flex(spec, codec):
|
||||
def _validate_flex(spec):
|
||||
from flex.core import parse as validate_flex
|
||||
from flex.exceptions import ValidationError
|
||||
try:
|
||||
validate_flex(spec)
|
||||
except ValidationError as ex:
|
||||
raise_from(SwaggerValidationError(str(ex), 'flex', spec, codec), ex)
|
||||
raise_from(SwaggerValidationError(str(ex)), ex)
|
||||
|
||||
|
||||
def _validate_swagger_spec_validator(spec, codec):
|
||||
def _validate_swagger_spec_validator(spec):
|
||||
from swagger_spec_validator.validator20 import validate_spec as validate_ssv
|
||||
from swagger_spec_validator.common import SwaggerValidationError as SSVErr
|
||||
try:
|
||||
validate_ssv(spec)
|
||||
except SSVErr as ex:
|
||||
raise_from(SwaggerValidationError(str(ex), 'swagger_spec_validator', spec, codec), ex)
|
||||
raise_from(SwaggerValidationError(str(ex)), ex)
|
||||
|
||||
|
||||
#:
|
||||
@@ -61,10 +60,17 @@ class _OpenAPICodec(object):
|
||||
raise TypeError('Expected a `openapi.Swagger` instance')
|
||||
|
||||
spec = self.generate_swagger_object(document)
|
||||
errors = {}
|
||||
for validator in self.validators:
|
||||
# validate a deepcopy of the spec to prevent the validator from messing with it
|
||||
# for example, swagger_spec_validator adds an x-scope property to all references
|
||||
VALIDATORS[validator](copy.deepcopy(spec), self)
|
||||
try:
|
||||
# validate a deepcopy of the spec to prevent the validator from messing with it
|
||||
# for example, swagger_spec_validator adds an x-scope property to all references
|
||||
VALIDATORS[validator](copy.deepcopy(spec))
|
||||
except SwaggerValidationError as e:
|
||||
errors[validator] = str(e)
|
||||
|
||||
if errors:
|
||||
raise SwaggerValidationError("spec validation failed", errors, spec, self)
|
||||
return force_bytes(self._dump_dict(spec))
|
||||
|
||||
def encode_error(self, err):
|
||||
@@ -87,7 +93,6 @@ class _OpenAPICodec(object):
|
||||
:return: swagger spec as dict
|
||||
:rtype: OrderedDict
|
||||
"""
|
||||
swagger.security_definitions = swagger_settings.SECURITY_DEFINITIONS
|
||||
return swagger.as_odict()
|
||||
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ class SwaggerError(Exception):
|
||||
|
||||
|
||||
class SwaggerValidationError(SwaggerError):
|
||||
def __init__(self, msg, validator_name, spec, source_codec, *args):
|
||||
def __init__(self, msg, errors=None, spec=None, source_codec=None, *args):
|
||||
super(SwaggerValidationError, self).__init__(msg, *args)
|
||||
self.validator_name = validator_name
|
||||
self.errors = errors
|
||||
self.spec = spec
|
||||
self.source_codec = source_codec
|
||||
|
||||
|
||||
+131
-42
@@ -1,25 +1,110 @@
|
||||
import logging
|
||||
import re
|
||||
from collections import OrderedDict, defaultdict
|
||||
|
||||
import uritemplate
|
||||
from coreapi.compat import urlparse
|
||||
from django.utils.encoding import force_text
|
||||
from rest_framework import versioning
|
||||
from rest_framework.compat import URLPattern, URLResolver, get_original_route
|
||||
from rest_framework.schemas.generators import EndpointEnumerator as _EndpointEnumerator
|
||||
from rest_framework.schemas.generators import SchemaGenerator
|
||||
from rest_framework.schemas.generators import SchemaGenerator, endpoint_ordering
|
||||
from rest_framework.schemas.inspectors import get_pk_description
|
||||
|
||||
from drf_yasg.errors import SwaggerGenerationError
|
||||
|
||||
from . import openapi
|
||||
from .app_settings import swagger_settings
|
||||
from .inspectors.field import get_basic_type_info, get_queryset_field
|
||||
from .openapi import ReferenceResolver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PATH_PARAMETER_RE = re.compile(r'{(?P<parameter>\w+)}')
|
||||
|
||||
|
||||
class EndpointEnumerator(_EndpointEnumerator):
|
||||
def __init__(self, patterns=None, urlconf=None, request=None):
|
||||
super(EndpointEnumerator, self).__init__(patterns, urlconf)
|
||||
self.request = request
|
||||
|
||||
def get_path_from_regex(self, path_regex):
|
||||
if path_regex.endswith(')'):
|
||||
logger.warning("url pattern does not end in $ ('%s') - unexpected things might happen",
|
||||
path_regex)
|
||||
return self.unescape_path(super(EndpointEnumerator, self).get_path_from_regex(path_regex))
|
||||
|
||||
def should_include_endpoint(self, path, callback, app_name='', namespace='', url_name=None):
|
||||
if not super(EndpointEnumerator, self).should_include_endpoint(path, callback):
|
||||
return False
|
||||
|
||||
version = getattr(self.request, 'version', None)
|
||||
versioning_class = getattr(callback.cls, 'versioning_class', None)
|
||||
if versioning_class is not None and issubclass(versioning_class, versioning.NamespaceVersioning):
|
||||
if version and version not in namespace.split(':'):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def replace_version(self, path, callback):
|
||||
"""If ``request.version`` is not ``None`` and `callback` uses ``URLPathVersioning``, this function replaces
|
||||
the ``version`` parameter in `path` with the actual version.
|
||||
|
||||
:param str path: the templated path
|
||||
:param callback: the view callback
|
||||
:rtype: str
|
||||
"""
|
||||
versioning_class = getattr(callback.cls, 'versioning_class', None)
|
||||
if versioning_class is not None and issubclass(versioning_class, versioning.URLPathVersioning):
|
||||
version = getattr(self.request, 'version', None)
|
||||
if version:
|
||||
version_param = getattr(versioning_class, 'version_param', 'version')
|
||||
version_param = '{%s}' % version_param
|
||||
if version_param not in path:
|
||||
logger.info("view %s uses URLPathVersioning but URL %s has no param %s"
|
||||
% (callback.cls, path, version_param))
|
||||
path = path.replace(version_param, version)
|
||||
|
||||
return path
|
||||
|
||||
def get_api_endpoints(self, patterns=None, prefix='', app_name=None, namespace=None):
|
||||
"""
|
||||
Return a list of all available API endpoints by inspecting the URL conf.
|
||||
|
||||
Copied entirely from super.
|
||||
"""
|
||||
if patterns is None:
|
||||
patterns = self.patterns
|
||||
|
||||
api_endpoints = []
|
||||
|
||||
for pattern in patterns:
|
||||
path_regex = prefix + get_original_route(pattern)
|
||||
if isinstance(pattern, URLPattern):
|
||||
path = self.get_path_from_regex(path_regex)
|
||||
callback = pattern.callback
|
||||
url_name = pattern.name
|
||||
if self.should_include_endpoint(path, callback, app_name or '', namespace or '', url_name):
|
||||
path = self.replace_version(path, callback)
|
||||
for method in self.get_allowed_methods(callback):
|
||||
endpoint = (path, method, callback)
|
||||
api_endpoints.append(endpoint)
|
||||
|
||||
elif isinstance(pattern, URLResolver):
|
||||
nested_endpoints = self.get_api_endpoints(
|
||||
patterns=pattern.url_patterns,
|
||||
prefix=path_regex,
|
||||
app_name="%s:%s" % (app_name, pattern.app_name) if app_name else pattern.app_name,
|
||||
namespace="%s:%s" % (namespace, pattern.namespace) if namespace else pattern.namespace
|
||||
)
|
||||
api_endpoints.extend(nested_endpoints)
|
||||
else:
|
||||
logger.warning("unknown pattern type {}".format(type(pattern)))
|
||||
|
||||
api_endpoints = sorted(api_endpoints, key=endpoint_ordering)
|
||||
|
||||
return api_endpoints
|
||||
|
||||
def unescape(self, s):
|
||||
"""Unescape all backslash escapes from `s`.
|
||||
|
||||
@@ -30,8 +115,8 @@ class EndpointEnumerator(_EndpointEnumerator):
|
||||
return re.sub(r'\\(.)', r'\1', s)
|
||||
|
||||
def unescape_path(self, path):
|
||||
"""Remove backslashes from all path components outside {parameters}. This is needed because
|
||||
Django>=2.0 ``path()``/``RoutePattern`` aggresively escapes all non-parameter path components.
|
||||
"""Remove backslashe escapes from all path components outside {parameters}. This is needed because
|
||||
``simplify_regex`` does not handle this correctly - note however that this implementation is
|
||||
|
||||
**NOTE:** this might destructively affect some url regex patterns that contain metacharacters (e.g. \w, \d)
|
||||
outside path parameter groups; if you are in this category, God help you
|
||||
@@ -60,12 +145,19 @@ class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
endpoint_enumerator_class = EndpointEnumerator
|
||||
|
||||
def __init__(self, info, version='', url=swagger_settings.DEFAULT_API_URL, patterns=None, urlconf=None):
|
||||
def __init__(self, info, version='', url=None, patterns=None, urlconf=None):
|
||||
"""
|
||||
|
||||
:param .Info info: information about the API
|
||||
:param str version: API version string; can be omitted to use `info.default_version`
|
||||
:param str url: API url; can be empty to remove URL info from the result
|
||||
:param str version: API version string; if omitted, `info.default_version` will be used
|
||||
:param str url: API scheme, host and port; if ``None`` is passed and ``DEFAULT_API_URL`` is not set, the url
|
||||
will be inferred from the request made against the schema view, so you should generally not need to set
|
||||
this parameter explicitly; if the empty string is passed, no host and scheme will be emitted
|
||||
|
||||
If `url` is not ``None`` or the empty string, it must be a scheme-absolute uri (i.e. starting with http://
|
||||
or https://), and any path component is ignored;
|
||||
|
||||
See also: :ref:`documentation on base URL construction <custom-spec-base-url>`
|
||||
:param patterns: if given, only these patterns will be enumerated for inclusion in the API spec
|
||||
:param urlconf: if patterns is not given, use this urlconf to enumerate patterns;
|
||||
if not given, the default urlconf is used
|
||||
@@ -73,6 +165,15 @@ class OpenAPISchemaGenerator(object):
|
||||
self._gen = SchemaGenerator(info.title, url, info.get('description', ''), patterns, urlconf)
|
||||
self.info = info
|
||||
self.version = version
|
||||
if url is None and swagger_settings.DEFAULT_API_URL is not None:
|
||||
url = swagger_settings.DEFAULT_API_URL
|
||||
|
||||
if url:
|
||||
parsed_url = urlparse.urlparse(url)
|
||||
if parsed_url.scheme not in ('http', 'https') or not parsed_url.netloc:
|
||||
raise SwaggerGenerationError("`url` must be an absolute HTTP(S) url")
|
||||
if parsed_url.path:
|
||||
logger.warning("path component of api base URL %s is ignored; use FORCE_SCRIPT_NAME instead" % url)
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
@@ -89,18 +190,23 @@ class OpenAPISchemaGenerator(object):
|
||||
:rtype: openapi.Swagger
|
||||
"""
|
||||
endpoints = self.get_endpoints(request)
|
||||
endpoints = self.replace_version(endpoints, request)
|
||||
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
|
||||
paths = self.get_paths(endpoints, components, request, public)
|
||||
paths, prefix = self.get_paths(endpoints, components, request, public)
|
||||
|
||||
url = self.url
|
||||
if not url and request is not None:
|
||||
if url is None and request is not None:
|
||||
url = request.build_absolute_uri()
|
||||
|
||||
return openapi.Swagger(
|
||||
swagger = openapi.Swagger(
|
||||
info=self.info, paths=paths,
|
||||
_url=url, _version=self.version, **dict(components)
|
||||
_url=url, _prefix=prefix, _version=self.version, **dict(components)
|
||||
)
|
||||
swagger.security_definitions = swagger_settings.SECURITY_DEFINITIONS
|
||||
security_requirements = swagger_settings.SECURITY_REQUIREMENTS
|
||||
if security_requirements is None:
|
||||
security_requirements = [{security_scheme: [] for security_scheme in swagger_settings.SECURITY_DEFINITIONS}]
|
||||
swagger.security = security_requirements
|
||||
return swagger
|
||||
|
||||
def create_view(self, callback, method, request=None):
|
||||
"""Create a view instance from a view callback as registered in urlpatterns.
|
||||
@@ -120,30 +226,6 @@ class OpenAPISchemaGenerator(object):
|
||||
setattr(view_method.__func__, '_swagger_auto_schema', overrides)
|
||||
return view
|
||||
|
||||
def replace_version(self, endpoints, request):
|
||||
"""If ``request.version`` is not ``None``, replace the version parameter in the path of any endpoints using
|
||||
``URLPathVersioning`` as a versioning class.
|
||||
|
||||
:param dict endpoints: endpoints as returned by :meth:`.get_endpoints`
|
||||
:param Request request: the request made against the schema view
|
||||
:return: endpoints with modified paths
|
||||
"""
|
||||
version = getattr(request, 'version', None)
|
||||
if version is None:
|
||||
return endpoints
|
||||
|
||||
new_endpoints = {}
|
||||
for path, endpoint in endpoints.items():
|
||||
view_cls = endpoint[0]
|
||||
versioning_class = getattr(view_cls, 'versioning_class', None)
|
||||
version_param = getattr(versioning_class, 'version_param', 'version')
|
||||
if versioning_class is not None and issubclass(versioning_class, versioning.URLPathVersioning):
|
||||
path = path.replace('{%s}' % version_param, version)
|
||||
|
||||
new_endpoints[path] = endpoint
|
||||
|
||||
return new_endpoints
|
||||
|
||||
def get_endpoints(self, request):
|
||||
"""Iterate over all the registered endpoints in the API and return a fake view with the right parameters.
|
||||
|
||||
@@ -151,7 +233,7 @@ class OpenAPISchemaGenerator(object):
|
||||
:return: {path: (view_class, list[(http_method, view_instance)])
|
||||
:rtype: dict
|
||||
"""
|
||||
enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf)
|
||||
enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf, request=request)
|
||||
endpoints = enumerator.get_api_endpoints()
|
||||
|
||||
view_paths = defaultdict(list)
|
||||
@@ -207,14 +289,16 @@ class OpenAPISchemaGenerator(object):
|
||||
:param ReferenceResolver components: resolver/container for Swagger References
|
||||
:param Request request: the request made against the schema view; can be None
|
||||
:param bool public: if True, all endpoints are included regardless of access through `request`
|
||||
:rtype: openapi.Paths
|
||||
:returns: the :class:`.Paths` object and the longest common path prefix, as a 2-tuple
|
||||
:rtype: tuple[openapi.Paths,str]
|
||||
"""
|
||||
if not endpoints:
|
||||
return openapi.Paths(paths={})
|
||||
return openapi.Paths(paths={}), ''
|
||||
|
||||
prefix = self.determine_path_prefix(list(endpoints.keys())) or ''
|
||||
assert '{' not in prefix, "base path cannot be templated in swagger 2.0"
|
||||
|
||||
prefix = self.determine_path_prefix(list(endpoints.keys()))
|
||||
paths = OrderedDict()
|
||||
|
||||
for path, (view_cls, methods) in sorted(endpoints.items()):
|
||||
operations = {}
|
||||
for method, view in methods:
|
||||
@@ -224,9 +308,14 @@ class OpenAPISchemaGenerator(object):
|
||||
operations[method.lower()] = self.get_operation(view, path, prefix, method, components, request)
|
||||
|
||||
if operations:
|
||||
paths[path] = self.get_path_item(path, view_cls, operations)
|
||||
# since the common prefix is used as the API basePath, it must be stripped
|
||||
# from individual paths when writing them into the swagger document
|
||||
path_suffix = path[len(prefix):]
|
||||
if not path_suffix.startswith('/'):
|
||||
path_suffix = '/' + path_suffix
|
||||
paths[path_suffix] = self.get_path_item(path, view_cls, operations)
|
||||
|
||||
return openapi.Paths(paths=paths)
|
||||
return openapi.Paths(paths=paths), prefix
|
||||
|
||||
def get_operation(self, view, path, prefix, method, components, request):
|
||||
"""Get an :class:`.Operation` for the given API endpoint (path, method). This method delegates to
|
||||
|
||||
@@ -462,8 +462,10 @@ else:
|
||||
"""Converts property names to camelCase if ``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer`` are used."""
|
||||
|
||||
def is_camel_case(self):
|
||||
return any(issubclass(parser, CamelCaseJSONParser) for parser in self.view.parser_classes) \
|
||||
or any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.view.renderer_classes)
|
||||
return (
|
||||
any(issubclass(parser, CamelCaseJSONParser) for parser in self.view.parser_classes) or
|
||||
any(issubclass(renderer, CamelCaseJSONRenderer) for renderer in self.view.renderer_classes)
|
||||
)
|
||||
|
||||
def process_result(self, result, method_name, obj, **kwargs):
|
||||
if isinstance(result, openapi.Schema.OR_REF) and self.is_camel_case():
|
||||
|
||||
@@ -27,6 +27,8 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
|
||||
operation_id = self.get_operation_id(operation_keys)
|
||||
description = self.get_description()
|
||||
security = self.get_security()
|
||||
assert security is None or isinstance(security, list), "security must be a list of securiy requirement objects"
|
||||
tags = self.get_tags(operation_keys)
|
||||
|
||||
responses = self.get_responses()
|
||||
@@ -38,6 +40,7 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
parameters=parameters,
|
||||
consumes=consumes,
|
||||
tags=tags,
|
||||
security=security
|
||||
)
|
||||
|
||||
def get_request_body_parameters(self, consumes):
|
||||
@@ -286,6 +289,16 @@ class SwaggerAutoSchema(ViewInspector):
|
||||
description = self._sch.get_description(self.path, self.method)
|
||||
return description
|
||||
|
||||
def get_security(self):
|
||||
"""Return a list of security requirements for this operation.
|
||||
|
||||
Returning an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
|
||||
authentication schemes). Returning ``None`` will inherit the top-level secuirty requirements.
|
||||
|
||||
:return: security requirements
|
||||
:rtype: list"""
|
||||
return self.overrides.get('security', None)
|
||||
|
||||
def get_tags(self, operation_keys):
|
||||
"""Get a list of tags for this operation. Tags determine how operations relate with each other, and in the UI
|
||||
each tag will show as a group containing the operations that use it.
|
||||
|
||||
@@ -42,7 +42,7 @@ class Command(BaseCommand):
|
||||
'-u', '--url', dest='api_url',
|
||||
default='',
|
||||
type=str,
|
||||
help='Base API URL - sets the host, scheme and basePath attributes of the generated document.'
|
||||
help='Base API URL - sets the host and scheme attributes of the generated document.'
|
||||
)
|
||||
parser.add_argument(
|
||||
'-m', '--mock-request', dest='mock',
|
||||
|
||||
@@ -13,7 +13,7 @@ class SwaggerExceptionMiddleware(object):
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
if isinstance(exception, SwaggerValidationError):
|
||||
err = {'errors': {exception.validator_name: str(exception)}}
|
||||
err = {'errors': exception.errors, 'message': str(exception)}
|
||||
codec = exception.source_codec
|
||||
if isinstance(codec, _OpenAPICodec):
|
||||
err = codec.encode_error(err)
|
||||
|
||||
+62
-11
@@ -2,6 +2,7 @@ import re
|
||||
from collections import OrderedDict
|
||||
|
||||
from coreapi.compat import urlparse
|
||||
from django.urls import get_script_prefix
|
||||
from inflection import camelize
|
||||
|
||||
from .utils import filter_none
|
||||
@@ -210,11 +211,13 @@ class Info(SwaggerDict):
|
||||
|
||||
|
||||
class Swagger(SwaggerDict):
|
||||
def __init__(self, info=None, _url=None, _version=None, paths=None, definitions=None, **extra):
|
||||
def __init__(self, info=None, _url=None, _prefix=None, _version=None, paths=None, definitions=None, **extra):
|
||||
"""Root Swagger object.
|
||||
|
||||
:param .Info info: info object
|
||||
:param str _url: URL used for guessing the API host, scheme and basepath
|
||||
:param str _url: URL used for setting the API host and scheme
|
||||
:param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi
|
||||
SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable
|
||||
:param str _version: version string to override Info
|
||||
:param .Paths paths: paths object
|
||||
:param dict[str,.Schema] definitions: named models
|
||||
@@ -226,16 +229,39 @@ class Swagger(SwaggerDict):
|
||||
|
||||
if _url:
|
||||
url = urlparse.urlparse(_url)
|
||||
if url.netloc:
|
||||
self.host = url.netloc
|
||||
if url.scheme:
|
||||
self.schemes = [url.scheme]
|
||||
self.base_path = '/'
|
||||
assert url.netloc and url.scheme, "if given, url must have both schema and netloc"
|
||||
self.host = url.netloc
|
||||
self.schemes = [url.scheme]
|
||||
|
||||
self.base_path = self.get_base_path(get_script_prefix(), _prefix)
|
||||
self.paths = paths
|
||||
self.definitions = filter_none(definitions)
|
||||
self._insert_extras__()
|
||||
|
||||
@classmethod
|
||||
def get_base_path(cls, script_prefix, api_prefix):
|
||||
"""Determine an appropriate value for ``basePath`` based on the SCRIPT_NAME and the api common prefix.
|
||||
|
||||
:param str script_prefix: script prefix as defined by django ``get_script_prefix``
|
||||
:param str api_prefix: api common prefix
|
||||
:return: joined base path
|
||||
"""
|
||||
# avoid double slash when joining script_name with api_prefix
|
||||
if script_prefix and script_prefix.endswith('/'):
|
||||
script_prefix = script_prefix[:-1]
|
||||
if not api_prefix.startswith('/'):
|
||||
api_prefix = '/' + api_prefix
|
||||
|
||||
base_path = script_prefix + api_prefix
|
||||
|
||||
# ensure that the base path has a leading slash and no trailing slash
|
||||
if base_path and base_path.endswith('/'):
|
||||
base_path = base_path[:-1]
|
||||
if not base_path.startswith('/'):
|
||||
base_path = '/' + base_path
|
||||
|
||||
return base_path
|
||||
|
||||
|
||||
class Paths(SwaggerDict):
|
||||
def __init__(self, paths, **extra):
|
||||
@@ -321,11 +347,15 @@ class Items(SwaggerDict):
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self._insert_extras__()
|
||||
if items and type != TYPE_ARRAY:
|
||||
raise AssertionError("items can only be used when type is array")
|
||||
if pattern and type != TYPE_STRING:
|
||||
raise AssertionError("pattern can only be used when type is string")
|
||||
|
||||
|
||||
class Parameter(SwaggerDict):
|
||||
def __init__(self, name, in_, description=None, required=None, schema=None,
|
||||
type=None, format=None, enum=None, pattern=None, items=None, **extra):
|
||||
type=None, format=None, enum=None, pattern=None, items=None, default=None, **extra):
|
||||
"""Describe parameters accepted by an :class:`.Operation`. Each parameter should be a unique combination of
|
||||
(`name`, `in_`). ``body`` and ``form`` parameters in the same operation are mutually exclusive.
|
||||
|
||||
@@ -339,6 +369,7 @@ class Parameter(SwaggerDict):
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param .Items items: only valid if `type` is ``array``
|
||||
:param default: default value if the parameter is not provided; must conform to parameter type
|
||||
"""
|
||||
super(Parameter, self).__init__(**extra)
|
||||
if (not schema and not type) or (schema and type):
|
||||
@@ -354,6 +385,18 @@ class Parameter(SwaggerDict):
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self._insert_extras__()
|
||||
if self['in'] == IN_PATH:
|
||||
# path parameters must always be required
|
||||
assert required is not False, "path parameter cannot be optional"
|
||||
self.required = True
|
||||
if self['in'] != IN_BODY and schema is not None:
|
||||
raise AssertionError("schema can only be applied to a body Parameter, not %s" % type)
|
||||
if (format or enum or pattern or default) and not type:
|
||||
raise AssertionError("[format, enum, pattern, default] can only be applied to non-body Parameter")
|
||||
if items and type != TYPE_ARRAY:
|
||||
raise AssertionError("items can only be used when type is array")
|
||||
if pattern and type != TYPE_STRING:
|
||||
raise AssertionError("pattern can only be used when type is string")
|
||||
|
||||
|
||||
class Schema(SwaggerDict):
|
||||
@@ -381,9 +424,9 @@ class Schema(SwaggerDict):
|
||||
super(Schema, self).__init__(**extra)
|
||||
if required is True or required is False:
|
||||
# common error
|
||||
raise AssertionError(
|
||||
"the `requires` attribute of schema must be an array of required properties, not a boolean!")
|
||||
assert type is not None, "type is required!"
|
||||
raise AssertionError("the `requires` attribute of schema must be an "
|
||||
"array of required property names, not a boolean!")
|
||||
assert type, "type is required!"
|
||||
self.title = title
|
||||
self.description = description
|
||||
self.required = filter_none(required)
|
||||
@@ -397,6 +440,14 @@ class Schema(SwaggerDict):
|
||||
self.read_only = read_only
|
||||
self.default = default
|
||||
self._insert_extras__()
|
||||
if (properties or (additional_properties is not None)) and type != TYPE_OBJECT:
|
||||
raise AssertionError("only object Schema can have properties")
|
||||
if (format or enum or pattern) and type in (TYPE_OBJECT, TYPE_ARRAY):
|
||||
raise AssertionError("[format, enum, pattern] can only be applied to primitive Schema")
|
||||
if items and type != TYPE_ARRAY:
|
||||
raise AssertionError("items can only be used when type is array")
|
||||
if pattern and type != TYPE_STRING:
|
||||
raise AssertionError("pattern can only be used when type is string")
|
||||
|
||||
|
||||
class _Ref(SwaggerDict):
|
||||
|
||||
@@ -9,7 +9,7 @@ from .codecs import VALIDATORS, OpenAPICodecJson, OpenAPICodecYaml
|
||||
class _SpecRenderer(BaseRenderer):
|
||||
"""Base class for text renderers. Handles encoding and validation."""
|
||||
charset = None
|
||||
validators = ['ssv', 'flex']
|
||||
validators = []
|
||||
codec_class = None
|
||||
|
||||
@classmethod
|
||||
@@ -117,3 +117,11 @@ class ReDocRenderer(_UIRenderer):
|
||||
"""
|
||||
template = 'drf-yasg/redoc.html'
|
||||
format = 'redoc'
|
||||
|
||||
|
||||
class ReDocAlphaRenderer(_UIRenderer):
|
||||
"""Renders a ReDoc web interface for schema browisng.
|
||||
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
|
||||
"""
|
||||
template = 'drf-yasg/redoc-alpha.html'
|
||||
format = 'redoc'
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
var redoc = document.createElement("redoc");
|
||||
redoc.setAttribute("spec-url", specURL);
|
||||
|
||||
var redocSettings = JSON.parse(document.getElementById('redoc-settings').innerHTML);
|
||||
if (redocSettings.lazyRendering) {
|
||||
redoc.setAttribute("lazy-rendering", '');
|
||||
}
|
||||
if (redocSettings.pathInMiddle) {
|
||||
redoc.setAttribute("path-in-middle-panel", '');
|
||||
}
|
||||
if (redocSettings.hideHostname) {
|
||||
redoc.setAttribute("hide-hostname", '');
|
||||
}
|
||||
redoc.setAttribute("expand-responses", redocSettings.expandResponses);
|
||||
document.body.appendChild(redoc);
|
||||
|
||||
function hideEmptyVersion() {
|
||||
// 'span.api-info-version' is for redoc 1.x, 'div.api-info span' is for redoc 2-alpha
|
||||
var apiVersion = document.querySelector('span.api-info-version') || document.querySelector('div.api-info span');
|
||||
if (!apiVersion) {
|
||||
console.log("WARNING: could not find API versionString element (span.api-info-version)");
|
||||
return;
|
||||
}
|
||||
|
||||
var versionString = apiVersion.innerText;
|
||||
if (versionString) {
|
||||
// trim spaces and surrounding ()
|
||||
versionString = versionString.replace(/ /g,'');
|
||||
versionString = versionString.replace(/(^\()|(\)$)/g,'');
|
||||
}
|
||||
|
||||
if (!versionString) {
|
||||
// hide version element if empty
|
||||
apiVersion.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
if (document.querySelector('span.api-info-version') || document.querySelector('div.api-info span')) {
|
||||
hideEmptyVersion();
|
||||
}
|
||||
else {
|
||||
insertionQ('span.api-info-version').every(hideEmptyVersion);
|
||||
insertionQ('div.api-info span').every(hideEmptyVersion);
|
||||
}
|
||||
+2
-2
File diff suppressed because one or more lines are too long
@@ -0,0 +1,77 @@
|
||||
html {
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
*,
|
||||
*:before,
|
||||
*:after {
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body.swagger-body {
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
#django-session-auth {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#django-session-auth > div {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize {
|
||||
padding: 10px 23px;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize a {
|
||||
color: #49cc90;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#django-session-auth .hello {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
#django-session-auth .hello .django-session {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: inline;
|
||||
padding: .2em .6em .3em;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
vertical-align: baseline;
|
||||
border-radius: .25em;
|
||||
}
|
||||
|
||||
.label-primary {
|
||||
background-color: #337ab7;
|
||||
}
|
||||
|
||||
.divider {
|
||||
margin-right: 8px;
|
||||
background: #16222c44;
|
||||
width: 2px;
|
||||
}
|
||||
|
||||
svg.swagger-defs {
|
||||
position: absolute;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,70 @@
|
||||
"use strict";
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
|
||||
function patchSwaggerUi() {
|
||||
var authWrapper = document.querySelector('.auth-wrapper');
|
||||
var authorizeButton = document.querySelector('.auth-wrapper .authorize');
|
||||
var djangoSessionAuth = document.querySelector('#django-session-auth');
|
||||
if (document.querySelector('.auth-wrapper #django-session-auth')) {
|
||||
console.log("WARNING: session auth already patched; skipping patchSwaggerUi()");
|
||||
return;
|
||||
}
|
||||
|
||||
authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
|
||||
djangoSessionAuth.classList.remove("hidden");
|
||||
|
||||
var divider = document.createElement("div");
|
||||
divider.classList.add("divider");
|
||||
authWrapper.insertBefore(divider, authorizeButton);
|
||||
}
|
||||
|
||||
function initSwaggerUi() {
|
||||
if (window.ui) {
|
||||
console.log("WARNING: skipping initSwaggerUi() because window.ui is already defined");
|
||||
return;
|
||||
}
|
||||
var swaggerConfig = {
|
||||
url: specURL,
|
||||
dom_id: '#swagger-ui',
|
||||
displayOperationId: true,
|
||||
displayRequestDuration: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout",
|
||||
filter: true,
|
||||
requestInterceptor: function(request) {
|
||||
var headers = request.headers || {};
|
||||
var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
|
||||
if (csrftoken) {
|
||||
headers["X-CSRFToken"] = csrftoken.value;
|
||||
}
|
||||
return request;
|
||||
}
|
||||
};
|
||||
|
||||
var swaggerSettings = JSON.parse(document.getElementById('swagger-settings').innerHTML);
|
||||
|
||||
for (var p in swaggerSettings) {
|
||||
if (swaggerSettings.hasOwnProperty(p)) {
|
||||
swaggerConfig[p] = swaggerSettings[p];
|
||||
}
|
||||
}
|
||||
window.ui = SwaggerUIBundle(swaggerConfig);
|
||||
}
|
||||
|
||||
window.onload = function () {
|
||||
initSwaggerUi();
|
||||
};
|
||||
|
||||
if (document.querySelector('.auth-wrapper .authorize')) {
|
||||
patchSwaggerUi();
|
||||
}
|
||||
else {
|
||||
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{ title }}</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
|
||||
</head>
|
||||
<body>
|
||||
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
|
||||
|
||||
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script>
|
||||
<script src="{% static 'drf-yasg/redoc-alpha/redoc.standalone.js' %}"> </script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -5,39 +5,14 @@
|
||||
<title>{{ title }}</title>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
{% if not request.version %}
|
||||
span.api-info-version {
|
||||
display: none;
|
||||
}
|
||||
{% endif %}
|
||||
</style>
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
var redoc = document.createElement("redoc");
|
||||
redoc.setAttribute("spec-url", specURL);
|
||||
<script id="redoc-settings" type="application/json">{{ redoc_settings | safe }}</script>
|
||||
|
||||
var redocSettings = {};
|
||||
redocSettings = {{ redoc_settings | safe }};
|
||||
if (redocSettings.lazyRendering) {
|
||||
redoc.setAttribute("lazy-rendering", '');
|
||||
}
|
||||
if (redocSettings.pathInMiddle) {
|
||||
redoc.setAttribute("path-in-middle-panel", '');
|
||||
}
|
||||
if (redocSettings.hideHostname) {
|
||||
redoc.setAttribute("hide-hostname", '');
|
||||
}
|
||||
redoc.setAttribute("expand-responses", redocSettings.expandResponses);
|
||||
document.body.appendChild(redoc);
|
||||
</script>
|
||||
<script src="{% static 'drf-yasg/redoc/redoc.min.js' %}"> </script>
|
||||
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/redoc-init.js' %}"> </script>
|
||||
<script src="{% static 'drf-yasg/redoc/redoc.min.js' %}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -5,88 +5,18 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ title }}</title>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700"
|
||||
rel="stylesheet">
|
||||
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700">
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/style.css' %}"/>
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'drf-yasg/swagger-ui-dist/swagger-ui.css' %}">
|
||||
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-32x32.png' %}"
|
||||
sizes="32x32"/>
|
||||
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-16x16.png' %}"
|
||||
sizes="16x16"/>
|
||||
<style>
|
||||
html {
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-32x32.png' %}" sizes="32x32"/>
|
||||
<link rel="icon" type="image/png" href="{% static 'drf-yasg/swagger-ui-dist/favicon-16x16.png' %}" sizes="16x16"/>
|
||||
|
||||
*,
|
||||
*:before,
|
||||
*:after {
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
#django-session-auth {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#django-session-auth > div {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize {
|
||||
padding: 10px 23px;
|
||||
}
|
||||
|
||||
#django-session-auth .btn.authorize a {
|
||||
color: #49cc90;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#django-session-auth .hello {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
#django-session-auth .hello .django-session {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: inline;
|
||||
padding: .2em .6em .3em;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
vertical-align: baseline;
|
||||
border-radius: .25em;
|
||||
}
|
||||
|
||||
.label-primary {
|
||||
background-color: #337ab7;
|
||||
}
|
||||
|
||||
.divider {
|
||||
margin-right: 8px;
|
||||
background: #16222c44;
|
||||
width: 2px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<body class="swagger-body">
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;width:0;height:0">
|
||||
<svg class="swagger-defs" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 20 20" id="unlocked">
|
||||
<path
|
||||
@@ -128,73 +58,13 @@
|
||||
<div id="swagger-ui"></div>
|
||||
<div id="spec-error" class="hidden alert alert-danger"></div>
|
||||
|
||||
<script>
|
||||
"use strict";
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
|
||||
function patchSwaggerUi() {
|
||||
var authWrapper = document.querySelector('.auth-wrapper');
|
||||
var authorizeButton = document.querySelector('.auth-wrapper .authorize');
|
||||
var djangoSessionAuth = document.querySelector('#django-session-auth');
|
||||
if (document.querySelector('.auth-wrapper #django-session-auth')) {
|
||||
console.log("session auth already patched");
|
||||
return;
|
||||
}
|
||||
|
||||
authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
|
||||
djangoSessionAuth.classList.remove("hidden");
|
||||
|
||||
var divider = document.createElement("div");
|
||||
divider.classList.add("divider");
|
||||
authWrapper.insertBefore(divider, authorizeButton);
|
||||
}
|
||||
|
||||
function initSwaggerUi() {
|
||||
var swaggerConfig = {
|
||||
url: specURL,
|
||||
dom_id: '#swagger-ui',
|
||||
displayOperationId: true,
|
||||
displayRequestDuration: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout",
|
||||
filter: true,
|
||||
requestInterceptor: function(request) {
|
||||
var headers = request.headers || {};
|
||||
var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]");
|
||||
if (csrftoken) {
|
||||
headers["X-CSRFToken"] = csrftoken.value;
|
||||
}
|
||||
return request;
|
||||
}
|
||||
};
|
||||
|
||||
var swaggerSettings = {};
|
||||
swaggerSettings = {{ swagger_settings | safe }};
|
||||
console.log(swaggerSettings);
|
||||
for (var p in swaggerSettings) {
|
||||
if (swaggerSettings.hasOwnProperty(p)) {
|
||||
swaggerConfig[p] = swaggerSettings[p];
|
||||
}
|
||||
}
|
||||
window.ui = SwaggerUIBundle(swaggerConfig);
|
||||
}
|
||||
|
||||
window.onload = function () {
|
||||
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
|
||||
initSwaggerUi();
|
||||
};
|
||||
</script>
|
||||
<script id="swagger-settings" type="application/json">{{ swagger_settings | safe }}</script>
|
||||
|
||||
<script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-bundle.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/swagger-ui-dist/swagger-ui-standalone-preset.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/insQ.min.js' %}"></script>
|
||||
<script src="{% static 'drf-yasg/swagger-ui-init.js' %}"></script>
|
||||
|
||||
<div id="django-session-auth" class="hidden">
|
||||
{% if USE_SESSION_AUTH %}
|
||||
|
||||
+11
-4
@@ -13,8 +13,8 @@ no_body = object()
|
||||
|
||||
|
||||
def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_body=None, query_serializer=None,
|
||||
manual_parameters=None, operation_id=None, operation_description=None, responses=None,
|
||||
field_inspectors=None, filter_inspectors=None, paginator_inspectors=None,
|
||||
manual_parameters=None, operation_id=None, operation_description=None, security=None,
|
||||
responses=None, field_inspectors=None, filter_inspectors=None, paginator_inspectors=None,
|
||||
**extra_overrides):
|
||||
"""Decorate a view method to customize the :class:`.Operation` object generated from it.
|
||||
|
||||
@@ -62,6 +62,9 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
|
||||
:param str operation_id: operation ID override; the operation ID must be unique accross the whole API
|
||||
:param str operation_description: operation description override
|
||||
:param str security: security requirements override; used to specify which authetication mechanism
|
||||
is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
|
||||
authentication schemes), and ``None`` will inherit the top-level secuirty requirements
|
||||
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
|
||||
keyed on response status code. If no success (``2xx``) response is given, one will automatically be
|
||||
generated from the request body and http method. If any ``2xx`` response is given the automatic response is
|
||||
@@ -94,6 +97,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
'manual_parameters': manual_parameters,
|
||||
'operation_id': operation_id,
|
||||
'operation_description': operation_description,
|
||||
'security': security,
|
||||
'responses': responses,
|
||||
'filter_inspectors': list(filter_inspectors) if filter_inspectors else None,
|
||||
'paginator_inspectors': list(paginator_inspectors) if paginator_inspectors else None,
|
||||
@@ -109,7 +113,7 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
bind_to_methods = getattr(view_method, 'bind_to_methods', [])
|
||||
# if the method is actually a function based view (@api_view), it will have a 'cls' attribute
|
||||
view_cls = getattr(view_method, 'cls', None)
|
||||
http_method_names = getattr(view_cls, 'http_method_names', [])
|
||||
http_method_names = [m for m in getattr(view_cls, 'http_method_names', []) if hasattr(view_cls, m)]
|
||||
|
||||
available_methods = http_method_names + bind_to_methods
|
||||
existing_data = getattr(view_method, '_swagger_auto_schema', {})
|
||||
@@ -138,13 +142,16 @@ def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_bod
|
||||
# for a single-method view we assume that single method as the decorator target
|
||||
_methods = _methods or available_methods
|
||||
|
||||
assert not any(hasattr(getattr(view_cls, mth, None), '_swagger_auto_schema') for mth in _methods), \
|
||||
"swagger_auto_schema applied twice to method"
|
||||
assert not any(mth in existing_data for mth in _methods), "swagger_auto_schema applied twice to method"
|
||||
existing_data.update((mth.lower(), data) for mth in _methods)
|
||||
view_method._swagger_auto_schema = existing_data
|
||||
else:
|
||||
assert not _methods, \
|
||||
"the methods argument should only be specified when decorating a detail_route or list_route; you " \
|
||||
"should also ensure that you put the swagger_auto_schema decorator AFTER (above) the _route decorator"
|
||||
assert not existing_data, "a single view method should only be decorated once"
|
||||
assert not existing_data, "swagger_auto_schema applied twice to method"
|
||||
view_method._swagger_auto_schema = data
|
||||
|
||||
return view_method
|
||||
|
||||
+10
-8
@@ -12,12 +12,15 @@ from rest_framework.views import APIView
|
||||
|
||||
from .app_settings import swagger_settings
|
||||
from .generators import OpenAPISchemaGenerator
|
||||
from .renderers import OpenAPIRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
|
||||
from .renderers import (
|
||||
OpenAPIRenderer, ReDocAlphaRenderer, ReDocRenderer, SwaggerJSONRenderer, SwaggerUIRenderer, SwaggerYAMLRenderer
|
||||
)
|
||||
|
||||
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
|
||||
UI_RENDERERS = {
|
||||
'swagger': (SwaggerUIRenderer, ReDocRenderer),
|
||||
'redoc': (ReDocRenderer, SwaggerUIRenderer),
|
||||
'redoc-alpha': (ReDocAlphaRenderer, ReDocRenderer, SwaggerUIRenderer)
|
||||
}
|
||||
|
||||
|
||||
@@ -49,14 +52,13 @@ def get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=Fal
|
||||
generator_class=OpenAPISchemaGenerator,
|
||||
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
|
||||
permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
|
||||
"""
|
||||
Create a SchemaView class with default renderers and generators.
|
||||
"""Create a SchemaView class with default renderers and generators.
|
||||
|
||||
:param .Info info: Swagger API Info object; if omitted, defaults to `DEFAULT_INFO`
|
||||
:param str url: API base url; if left blank will be deduced from the location the view is served at
|
||||
:param patterns: passed to SchemaGenerator
|
||||
:param urlconf: passed to SchemaGenerator
|
||||
:param bool public: if False, includes only endpoints the current user has access to
|
||||
:param .Info info: information about the API; if omitted, defaults to :ref:`DEFAULT_INFO <default-swagger-settings>`
|
||||
:param str url: same as :class:`.OpenAPISchemaGenerator`
|
||||
:param patterns: same as :class:`.OpenAPISchemaGenerator`
|
||||
:param urlconf: same as :class:`.OpenAPISchemaGenerator`
|
||||
:param bool public: if False, includes only the endpoints that are accesible by the user viewing the schema
|
||||
:param list validators: a list of validator names to apply; allowed values are ``flex``, ``ssv``
|
||||
:param type generator_class: schema generator class to use; should be a subclass of :class:`.OpenAPISchemaGenerator`
|
||||
:param tuple authentication_classes: authentication classes for the schema view itself
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
from __future__ import print_function
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.db.utils import IntegrityError
|
||||
|
||||
username = 'admin'
|
||||
email = 'admin@admin.admin'
|
||||
password = 'passwordadmin'
|
||||
User.objects.filter(username=username).delete()
|
||||
User.objects.create_superuser(username, email, password)
|
||||
|
||||
print("Created superuser '%s <%s>' with password '%s'" % (username, email, password))
|
||||
try:
|
||||
User.objects.create_superuser(username, email, password)
|
||||
except IntegrityError:
|
||||
print("User '%s <%s>' already exists" % (username, email))
|
||||
else:
|
||||
print("Created superuser '%s <%s>' with password '%s'" % (username, email, password))
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings.local")
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError:
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
drf-yasg[validation]
|
||||
Django>=1.11.7
|
||||
..[validation]
|
||||
-r ../requirements/testproj.txt
|
||||
|
||||
@@ -3,7 +3,9 @@ from djangorestframework_camel_case.render import CamelCaseJSONRenderer
|
||||
from inflection import camelize
|
||||
from rest_framework import generics
|
||||
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.inspectors import SwaggerAutoSchema
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
|
||||
@@ -53,6 +55,14 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
"""patch method docstring"""
|
||||
return super(SnippetDetail, self).patch(request, *args, **kwargs)
|
||||
|
||||
@swagger_auto_schema(manual_parameters=[
|
||||
openapi.Parameter(
|
||||
name='id', in_=openapi.IN_PATH,
|
||||
type=openapi.TYPE_INTEGER,
|
||||
description="path parameter override",
|
||||
required=True
|
||||
)
|
||||
])
|
||||
def delete(self, request, *args, **kwargs):
|
||||
"""delete method docstring"""
|
||||
return super(SnippetDetail, self).patch(request, *args, **kwargs)
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
import os
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '!z1yj(9uz)zk0gg@5--j)bc4h^i!8))r^dezco8glf190e0&#p'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
ALLOWED_HOSTS = [
|
||||
'127.0.0.1',
|
||||
@@ -69,16 +60,6 @@ TEMPLATES = [
|
||||
|
||||
WSGI_APPLICATION = 'testproj.wsgi.application'
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
|
||||
|
||||
@@ -97,16 +78,19 @@ AUTH_PASSWORD_VALIDATORS = [
|
||||
},
|
||||
]
|
||||
|
||||
# Django Rest Framework
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
)
|
||||
}
|
||||
|
||||
# drf-yasg
|
||||
|
||||
SWAGGER_SETTINGS = {
|
||||
'LOGIN_URL': '/admin/login',
|
||||
'LOGOUT_URL': '/admin/logout',
|
||||
'VALIDATOR_URL': 'http://localhost:8189',
|
||||
|
||||
'DEFAULT_INFO': 'testproj.urls.swagger_info'
|
||||
}
|
||||
@@ -128,9 +112,14 @@ USE_TZ = True
|
||||
# https://docs.djangoproject.com/en/1.11/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
|
||||
|
||||
# Testing
|
||||
|
||||
TEST_RUNNER = 'testproj.runner.PytestTestRunner'
|
||||
|
||||
# Logging configuration
|
||||
|
||||
LOGGING = {
|
||||
'version': 1,
|
||||
'disable_existing_loggers': True,
|
||||
@@ -0,0 +1,35 @@
|
||||
import dj_database_url
|
||||
|
||||
from .base import * # noqa: F403
|
||||
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS.append('.herokuapp.com')
|
||||
|
||||
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
|
||||
assert SECRET_KEY, 'DJANGO_SECRET_KEY environment variable must be set'
|
||||
|
||||
SESSION_COOKIE_SECURE = True
|
||||
CSRF_COOKIE_SECURE = True
|
||||
|
||||
SECURE_BROWSER_XSS_FILTER = True
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
X_FRAME_OPTIONS = 'DENY'
|
||||
|
||||
# Simplified static file serving.
|
||||
# https://warehouse.python.org/project/whitenoise/
|
||||
|
||||
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
||||
MIDDLEWARE.insert(0, 'whitenoise.middleware.WhiteNoiseMiddleware')
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': dj_database_url.config(conn_max_age=600)
|
||||
}
|
||||
|
||||
SILENCED_SYSTEM_CHECKS = [
|
||||
'security.W004', # SECURE_HSTS_SECONDS
|
||||
'security.W008', # SECURE_SSL_REDIRECT
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
|
||||
import dj_database_url
|
||||
|
||||
from .base import * # noqa: F403
|
||||
|
||||
SWAGGER_SETTINGS.update({'VALIDATOR_URL': 'http://localhost:8189'})
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
|
||||
|
||||
db_path = os.path.join(BASE_DIR, 'db.sqlite3')
|
||||
DATABASES = {
|
||||
'default': dj_database_url.parse('sqlite:///' + db_path)
|
||||
}
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '!z1yj(9uz)zk0gg@5--j)bc4h^i!8))r^dezco8glf190e0&#p'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
@@ -1,5 +1,7 @@
|
||||
import user_agents
|
||||
from django.conf.urls import include, url
|
||||
from django.contrib import admin
|
||||
from django.shortcuts import redirect
|
||||
from rest_framework import permissions
|
||||
from rest_framework.decorators import api_view
|
||||
|
||||
@@ -9,7 +11,13 @@ from drf_yasg.views import get_schema_view
|
||||
swagger_info = openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
description="Test description",
|
||||
description="""This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg) Django Rest Framework library.
|
||||
|
||||
The `swagger-ui` view can be found [here](/cached/swagger).
|
||||
The `ReDoc` view can be found [here](/cached/redoc).
|
||||
The swagger YAML document can be found [here](/cached/swagger.yaml).
|
||||
|
||||
You can log in using the pre-existing `admin` user with password `passwordadmin`.""", # noqa
|
||||
terms_of_service="https://www.google.com/policies/terms/",
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
@@ -27,14 +35,29 @@ def plain_view(request):
|
||||
pass
|
||||
|
||||
|
||||
def root_redirect(request):
|
||||
user_agent_string = request.META.get('HTTP_USER_AGENT', '')
|
||||
user_agent = user_agents.parse(user_agent_string)
|
||||
|
||||
if user_agent.is_mobile:
|
||||
schema_view = 'cschema-redoc'
|
||||
else:
|
||||
schema_view = 'cschema-swagger-ui'
|
||||
|
||||
return redirect(schema_view, permanent=True)
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=0), name='schema-json'),
|
||||
url(r'^swagger/$', SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
|
||||
url(r'^redoc/$', SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
|
||||
url(r'^redoc-alpha/$', SchemaView.with_ui('redoc-alpha', cache_timeout=0), name='schema-redoc-alpha'),
|
||||
url(r'^cached/swagger(?P<format>.json|.yaml)$', SchemaView.without_ui(cache_timeout=None), name='cschema-json'),
|
||||
url(r'^cached/swagger/$', SchemaView.with_ui('swagger', cache_timeout=None), name='cschema-swagger-ui'),
|
||||
url(r'^cached/redoc/$', SchemaView.with_ui('redoc', cache_timeout=None), name='cschema-redoc'),
|
||||
|
||||
url(r'^$', root_redirect),
|
||||
|
||||
url(r'^admin/', admin.site.urls),
|
||||
url(r'^snippets/', include('snippets.urls')),
|
||||
url(r'^articles/', include('articles.urls')),
|
||||
|
||||
@@ -2,6 +2,6 @@ import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings.local")
|
||||
|
||||
application = get_wsgi_application()
|
||||
|
||||
+11
-7
@@ -19,13 +19,17 @@ class UserList(APIView):
|
||||
serializer = UserSerializerrr(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
@swagger_auto_schema(operation_description="apiview post description override", request_body=openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
required=['username'],
|
||||
properties={
|
||||
'username': openapi.Schema(type=openapi.TYPE_STRING)
|
||||
},
|
||||
))
|
||||
@swagger_auto_schema(
|
||||
operation_description="apiview post description override",
|
||||
request_body=openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
required=['username'],
|
||||
properties={
|
||||
'username': openapi.Schema(type=openapi.TYPE_STRING)
|
||||
},
|
||||
),
|
||||
security=[]
|
||||
)
|
||||
def post(self, request):
|
||||
serializer = UserSerializerrr(request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
+14
-2
@@ -1,7 +1,11 @@
|
||||
swagger: '2.0'
|
||||
info:
|
||||
title: Snippets API
|
||||
description: Test description
|
||||
description: "This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg)\
|
||||
\ Django Rest Framework library.\n\nThe `swagger-ui` view can be found [here](/cached/swagger).\
|
||||
\ \nThe `ReDoc` view can be found [here](/cached/redoc). \nThe swagger YAML\
|
||||
\ document can be found [here](/cached/swagger.yaml). \n\nYou can log in using\
|
||||
\ the pre-existing `admin` user with password `passwordadmin`."
|
||||
termsOfService: https://www.google.com/policies/terms/
|
||||
contact:
|
||||
email: contact@snippets.local
|
||||
@@ -335,7 +339,12 @@ paths:
|
||||
delete:
|
||||
operationId: snippetsDelete
|
||||
description: delete method docstring
|
||||
parameters: []
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
description: path parameter override
|
||||
required: true
|
||||
type: integer
|
||||
responses:
|
||||
'204':
|
||||
description: ''
|
||||
@@ -403,6 +412,7 @@ paths:
|
||||
- application/json
|
||||
tags:
|
||||
- users
|
||||
security: []
|
||||
patch:
|
||||
operationId: users_dummy
|
||||
description: dummy operation
|
||||
@@ -1114,3 +1124,5 @@ definitions:
|
||||
securityDefinitions:
|
||||
basic:
|
||||
type: basic
|
||||
security:
|
||||
- basic: []
|
||||
|
||||
@@ -5,6 +5,7 @@ import pytest
|
||||
|
||||
from drf_yasg import codecs, openapi
|
||||
from drf_yasg.codecs import yaml_sane_load
|
||||
from drf_yasg.errors import SwaggerGenerationError
|
||||
from drf_yasg.generators import OpenAPISchemaGenerator
|
||||
|
||||
|
||||
@@ -46,14 +47,35 @@ def test_yaml_and_json_match(codec_yaml, codec_json, swagger):
|
||||
|
||||
|
||||
def test_basepath_only(mock_schema_request):
|
||||
with pytest.raises(SwaggerGenerationError):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='/basepath/',
|
||||
)
|
||||
|
||||
generator.get_schema(mock_schema_request, public=True)
|
||||
|
||||
|
||||
def test_no_netloc(mock_schema_request):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='/basepath/',
|
||||
url='',
|
||||
)
|
||||
|
||||
swagger = generator.get_schema(mock_schema_request, public=True)
|
||||
assert 'host' not in swagger
|
||||
assert 'schemes' not in swagger
|
||||
assert swagger['basePath'] == '/' # base path is not implemented for now
|
||||
assert 'host' not in swagger and 'schemes' not in swagger
|
||||
assert swagger['info']['version'] == 'v2'
|
||||
|
||||
|
||||
def test_securiy_requirements(swagger_settings, mock_schema_request):
|
||||
generator = OpenAPISchemaGenerator(
|
||||
info=openapi.Info(title="Test generator", default_version="v1"),
|
||||
version="v2",
|
||||
url='',
|
||||
)
|
||||
swagger_settings['SECURITY_REQUIREMENTS'] = []
|
||||
|
||||
swagger = generator.get_schema(mock_schema_request, public=True)
|
||||
assert swagger['security'] == []
|
||||
|
||||
+15
-18
@@ -4,24 +4,25 @@ from drf_yasg.codecs import yaml_sane_load
|
||||
|
||||
|
||||
def _get_versioned_schema(prefix, client, validate_schema):
|
||||
response = client.get(prefix + 'swagger.yaml')
|
||||
response = client.get(prefix + '/swagger.yaml')
|
||||
assert response.status_code == 200
|
||||
swagger = yaml_sane_load(response.content.decode('utf-8'))
|
||||
assert swagger['basePath'] == prefix
|
||||
validate_schema(swagger)
|
||||
assert prefix + 'snippets/' in swagger['paths']
|
||||
assert '/snippets/' in swagger['paths']
|
||||
return swagger
|
||||
|
||||
|
||||
def _check_v1(swagger, prefix):
|
||||
def _check_v1(swagger):
|
||||
assert swagger['info']['version'] == '1.0'
|
||||
versioned_post = swagger['paths'][prefix + 'snippets/']['post']
|
||||
versioned_post = swagger['paths']['/snippets/']['post']
|
||||
assert versioned_post['responses']['201']['schema']['$ref'] == '#/definitions/Snippet'
|
||||
assert 'v2field' not in swagger['definitions']['Snippet']['properties']
|
||||
|
||||
|
||||
def _check_v2(swagger, prefix):
|
||||
def _check_v2(swagger):
|
||||
assert swagger['info']['version'] == '2.0'
|
||||
versioned_post = swagger['paths'][prefix + 'snippets/']['post']
|
||||
versioned_post = swagger['paths']['/snippets/']['post']
|
||||
assert versioned_post['responses']['201']['schema']['$ref'] == '#/definitions/SnippetV2'
|
||||
assert 'v2field' in swagger['definitions']['SnippetV2']['properties']
|
||||
v2field = swagger['definitions']['SnippetV2']['properties']['v2field']
|
||||
@@ -30,27 +31,23 @@ def _check_v2(swagger, prefix):
|
||||
|
||||
@pytest.mark.urls('urlconfs.url_versioning')
|
||||
def test_url_v1(client, validate_schema):
|
||||
prefix = '/versioned/url/v1.0/'
|
||||
swagger = _get_versioned_schema(prefix, client, validate_schema)
|
||||
_check_v1(swagger, prefix)
|
||||
swagger = _get_versioned_schema('/versioned/url/v1.0', client, validate_schema)
|
||||
_check_v1(swagger)
|
||||
|
||||
|
||||
@pytest.mark.urls('urlconfs.url_versioning')
|
||||
def test_url_v2(client, validate_schema):
|
||||
prefix = '/versioned/url/v2.0/'
|
||||
swagger = _get_versioned_schema(prefix, client, validate_schema)
|
||||
_check_v2(swagger, prefix)
|
||||
swagger = _get_versioned_schema('/versioned/url/v2.0', client, validate_schema)
|
||||
_check_v2(swagger)
|
||||
|
||||
|
||||
@pytest.mark.urls('urlconfs.ns_versioning')
|
||||
def test_ns_v1(client, validate_schema):
|
||||
prefix = '/versioned/ns/v1.0/'
|
||||
swagger = _get_versioned_schema(prefix, client, validate_schema)
|
||||
_check_v1(swagger, prefix)
|
||||
swagger = _get_versioned_schema('/versioned/ns/v1.0', client, validate_schema)
|
||||
_check_v1(swagger)
|
||||
|
||||
|
||||
@pytest.mark.urls('urlconfs.ns_versioning')
|
||||
def test_ns_v2(client, validate_schema):
|
||||
prefix = '/versioned/ns/v2.0/'
|
||||
swagger = _get_versioned_schema(prefix, client, validate_schema)
|
||||
_check_v2(swagger, prefix)
|
||||
swagger = _get_versioned_schema('/versioned/ns/v2.0', client, validate_schema)
|
||||
_check_v2(swagger)
|
||||
|
||||
@@ -17,7 +17,7 @@ class SnippetListV2(SnippetListV1):
|
||||
serializer_class = SnippetSerializerV2
|
||||
|
||||
|
||||
app_name = 'test_ns_versioning'
|
||||
app_name = '2.0'
|
||||
|
||||
urlpatterns = [
|
||||
url(r"^$", SnippetListV2.as_view())
|
||||
|
||||
@@ -19,7 +19,7 @@ schema_patterns = [
|
||||
|
||||
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, namespace='2.0')),
|
||||
url(VERSION_PREFIX_NS + r"v2.0/snippets/", include(ns_version2)),
|
||||
url(VERSION_PREFIX_NS + r'v1.0/', include((schema_patterns, '1.0'))),
|
||||
url(VERSION_PREFIX_NS + r'v2.0/', include((schema_patterns, '2.0'))),
|
||||
]
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
[tox]
|
||||
envlist =
|
||||
py27-drf37,
|
||||
py{34,35,36,37}-drf37,
|
||||
py27-django111-drf37,
|
||||
py{34,35,36}-django{111,20}-drf37,
|
||||
py36-drfmaster,
|
||||
flake8, docs
|
||||
lint, docs
|
||||
|
||||
[travis:env]
|
||||
DRF =
|
||||
@@ -12,34 +12,29 @@ DRF =
|
||||
|
||||
[testenv]
|
||||
deps =
|
||||
drf37: djangorestframework>=3.7.3,<3.8
|
||||
django111: Django>=1.11,<2.0
|
||||
django20: Django>=2.0,<2.1
|
||||
|
||||
# py27 is tested with Django <2.0 (Django 2.0 no longer supports python 2)
|
||||
py27: Django>=1.11,<2.0
|
||||
drf37: djangorestframework>=3.7.7,<3.8
|
||||
|
||||
# main testing configurations
|
||||
py{34,35,36,37}-drf37: Django>=1.11,<2.1
|
||||
|
||||
# py3 with the latest build of Django and django-rest-framework to get early warning of compatibility issues
|
||||
# test with the latest build of Django and django-rest-framework to get early warning of compatibility issues
|
||||
drfmaster: https://github.com/encode/django-rest-framework/archive/master.tar.gz
|
||||
drfmaster: https://github.com/django/django/archive/master.tar.gz
|
||||
|
||||
# other dependencies
|
||||
-rrequirements/base.txt
|
||||
-rrequirements/validation.txt
|
||||
-rrequirements/test.txt
|
||||
|
||||
commands =
|
||||
pytest --cov-config .coveragerc --cov-append --cov {posargs}
|
||||
pytest --cov --cov-config .coveragerc --cov-append --cov-report="" {posargs}
|
||||
|
||||
[testenv:py36-drfmaster]
|
||||
pip_pre = True
|
||||
|
||||
[testenv:flake8]
|
||||
[testenv:lint]
|
||||
skip_install = true
|
||||
deps =
|
||||
flake8
|
||||
flake8-isort
|
||||
-rrequirements/lint.txt
|
||||
commands =
|
||||
flake8 src/drf_yasg testproj tests setup.py
|
||||
|
||||
@@ -48,15 +43,17 @@ deps =
|
||||
-rrequirements/docs.txt
|
||||
commands =
|
||||
python setup.py check --restructuredtext --metadata --strict
|
||||
sphinx-build -WnEa -b html docs docs\_build\html
|
||||
sphinx-build -WnEa -b html docs docs/_build/html
|
||||
|
||||
[pytest]
|
||||
DJANGO_SETTINGS_MODULE = testproj.settings
|
||||
DJANGO_SETTINGS_MODULE = testproj.settings.local
|
||||
python_paths = testproj
|
||||
addopts = -n 3
|
||||
|
||||
[flake8]
|
||||
max-line-length = 120
|
||||
exclude = **/migrations/*
|
||||
ignore = F405
|
||||
|
||||
[isort]
|
||||
skip = .eggs,.tox,docs,env,venv
|
||||
@@ -70,6 +67,7 @@ known_standard_library =
|
||||
collections,copy,distutils,functools,inspect,io,json,logging,operator,os,pkg_resources,re,setuptools,sys,
|
||||
types,warnings
|
||||
known_third_party =
|
||||
coreapi,coreschema,datadiff,django,django_filters,djangorestframework_camel_case,flex,inflection,pygments,
|
||||
pytest,rest_framework,ruamel,setuptools_scm,swagger_spec_validator,uritemplate
|
||||
coreapi,coreschema,datadiff,dj_database_url,django,django_filters,djangorestframework_camel_case,flex,gunicorn,
|
||||
inflection,pygments,pytest,rest_framework,ruamel,setuptools_scm,swagger_spec_validator,uritemplate,user_agents,
|
||||
whitenoise
|
||||
known_first_party = drf_yasg,testproj,articles,snippets,users,urlconfs
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/bin/bash
|
||||
set -ev
|
||||
npm update
|
||||
cp node_modules/redoc/dist/redoc.min.js src/drf_yasg/static/drf-yasg/redoc/redoc.min.js
|
||||
|
||||
cp node_modules/redoc/dist/redoc.min.js src/drf_yasg/static/drf-yasg/redoc/
|
||||
cp -r node_modules/swagger-ui-dist src/drf_yasg/static/drf-yasg/
|
||||
pushd src/drf_yasg/static/drf-yasg/swagger-ui-dist/ >/dev/null
|
||||
rm -f package.json .npmignore README.md
|
||||
|
||||
Reference in New Issue
Block a user