Add dcumentation (#12)
* added sphinx documentation * filled in most missing docstrings * updated README and setup.py, added CONTRIBUTING * added docs build target
This commit is contained in:
@@ -30,12 +30,14 @@ REDOC_DEFAULTS = {
|
||||
|
||||
IMPORT_STRINGS = []
|
||||
|
||||
#:
|
||||
swagger_settings = APISettings(
|
||||
user_settings=getattr(settings, 'SWAGGER_SETTINGS', {}),
|
||||
defaults=SWAGGER_DEFAULTS,
|
||||
import_strings=IMPORT_STRINGS,
|
||||
)
|
||||
|
||||
#:
|
||||
redoc_settings = APISettings(
|
||||
user_settings=getattr(settings, 'REDOC_SETTINGS', {}),
|
||||
defaults=REDOC_DEFAULTS,
|
||||
|
||||
@@ -29,6 +29,7 @@ def _validate_swagger_spec_validator(spec, codec):
|
||||
raise_from(SwaggerValidationError(str(ex), 'swagger_spec_validator', spec, codec), ex)
|
||||
|
||||
|
||||
#:
|
||||
VALIDATORS = {
|
||||
'flex': _validate_flex,
|
||||
'ssv': _validate_swagger_spec_validator,
|
||||
@@ -36,17 +37,28 @@ VALIDATORS = {
|
||||
|
||||
|
||||
class _OpenAPICodec(object):
|
||||
format = 'openapi'
|
||||
media_type = None
|
||||
|
||||
#: Allows easier mocking of settings
|
||||
settings = swagger_settings
|
||||
|
||||
def __init__(self, validators):
|
||||
self._validators = validators
|
||||
|
||||
@property
|
||||
def validators(self):
|
||||
"""List of validator names to apply"""
|
||||
return self._validators
|
||||
|
||||
def encode(self, document, **_):
|
||||
def encode(self, document):
|
||||
"""Transform an :class:`.Swagger` object to a sequence of bytes.
|
||||
|
||||
Also performs validation and applies settings.
|
||||
|
||||
:param openapi.Swagger document: Swagger spec object as generated by :class:`.OpenAPISchemaGenerator`
|
||||
:return: binary encoding of ``document``
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not isinstance(document, openapi.Swagger):
|
||||
raise TypeError('Expected a `openapi.Swagger` instance')
|
||||
|
||||
@@ -58,19 +70,26 @@ class _OpenAPICodec(object):
|
||||
return force_bytes(self._dump_dict(spec))
|
||||
|
||||
def encode_error(self, err):
|
||||
"""Dump an error message into an encoding-appropriate sequence of bytes"""
|
||||
return force_bytes(self._dump_dict(err))
|
||||
|
||||
def _dump_dict(self, spec):
|
||||
"""Dump the given dictionary into its string representation.
|
||||
|
||||
:param dict spec: a python dict
|
||||
:return: string representation of ``spec``
|
||||
:rtype: str
|
||||
"""
|
||||
raise NotImplementedError("override this method")
|
||||
|
||||
def generate_swagger_object(self, swagger):
|
||||
"""
|
||||
Generates the root Swagger object.
|
||||
"""Generates the root Swagger object.
|
||||
|
||||
:param openapi.Swagger swagger:
|
||||
:return OrderedDict: swagger spec as dict
|
||||
:param openapi.Swagger swagger: Swagger spec object as generated by :class:`.OpenAPISchemaGenerator`
|
||||
:return: swagger spec as dict
|
||||
:rtype: OrderedDict
|
||||
"""
|
||||
swagger.security_definitions = swagger_settings.SECURITY_DEFINITIONS
|
||||
swagger.security_definitions = self.settings.SECURITY_DEFINITIONS
|
||||
return swagger
|
||||
|
||||
|
||||
@@ -78,12 +97,16 @@ class OpenAPICodecJson(_OpenAPICodec):
|
||||
media_type = 'application/json'
|
||||
|
||||
def _dump_dict(self, spec):
|
||||
"""Dump ``spec`` into JSON."""
|
||||
return json.dumps(spec)
|
||||
|
||||
|
||||
class SaneYamlDumper(yaml.SafeDumper):
|
||||
"""YamlDumper class usable for dumping ``OrderedDict`` and list instances in a standard way."""
|
||||
|
||||
def increase_indent(self, flow=False, indentless=False, **kwargs):
|
||||
"""https://stackoverflow.com/a/39681672
|
||||
|
||||
Indent list elements.
|
||||
"""
|
||||
return super(SaneYamlDumper, self).increase_indent(flow=flow, indentless=False, **kwargs)
|
||||
@@ -91,10 +114,10 @@ class SaneYamlDumper(yaml.SafeDumper):
|
||||
@staticmethod
|
||||
def represent_odict(dump, mapping, flow_style=None): # pragma: no cover
|
||||
"""https://gist.github.com/miracle2k/3184458
|
||||
|
||||
Make PyYAML output an OrderedDict.
|
||||
|
||||
It will do so fine if you use yaml.dump(), but that generates ugly,
|
||||
non-standard YAML code.
|
||||
It will do so fine if you use yaml.dump(), but that generates ugly, non-standard YAML code.
|
||||
|
||||
To use yaml.safe_dump(), you need the following.
|
||||
"""
|
||||
@@ -130,4 +153,5 @@ class OpenAPICodecYaml(_OpenAPICodec):
|
||||
media_type = 'application/yaml'
|
||||
|
||||
def _dump_dict(self, spec):
|
||||
"""Dump ``spec`` into YAML."""
|
||||
return yaml.dump(spec, Dumper=SaneYamlDumper, default_flow_style=False, encoding='utf-8')
|
||||
|
||||
@@ -18,13 +18,29 @@ class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
|
||||
def __init__(self, info, version, url=None, patterns=None, urlconf=None):
|
||||
"""
|
||||
|
||||
:param .Info info: information about the API
|
||||
:param str version: API version string, takes preedence over the version in `info`
|
||||
:param str url: API
|
||||
:param 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
|
||||
"""
|
||||
self._gen = SchemaGenerator(info.title, url, info.get('description', ''), patterns, urlconf)
|
||||
self.info = info
|
||||
self.version = version
|
||||
self.url = url
|
||||
|
||||
def get_schema(self, request=None, public=False):
|
||||
"""Generate an openapi.Swagger representing the API schema."""
|
||||
"""Generate an :class:`.Swagger` representing the API schema.
|
||||
|
||||
:param rest_framework.request.Request request: the request used for filtering
|
||||
accesible endpoints and finding the spec URI
|
||||
:param bool public: if True, all endpoints are included regardless of access through `request`
|
||||
|
||||
:return: the generated Swagger specification
|
||||
:rtype: openapi.Swagger
|
||||
"""
|
||||
endpoints = self.get_endpoints(None if public else request)
|
||||
components = ReferenceResolver(openapi.SCHEMA_DEFINITIONS)
|
||||
paths = self.get_paths(endpoints, components)
|
||||
@@ -35,11 +51,17 @@ class OpenAPISchemaGenerator(object):
|
||||
|
||||
return openapi.Swagger(
|
||||
info=self.info, paths=paths,
|
||||
_url=url, _version=self.version, **components
|
||||
_url=url, _version=self.version, **dict(components)
|
||||
)
|
||||
|
||||
def create_view(self, callback, method, request=None):
|
||||
"""Create a view instance from a view callback as registered in urlpatterns."""
|
||||
"""Create a view instance from a view callback as registered in urlpatterns.
|
||||
|
||||
:param callable callback: view callback registered in urlpatterns
|
||||
:param str method: HTTP method
|
||||
:param rest_framework.request.Request request: request to bind to the view
|
||||
:return: the view instance
|
||||
"""
|
||||
view = self._gen.create_view(callback, method, request)
|
||||
overrides = getattr(callback, 'swagger_auto_schema', None)
|
||||
if overrides is not None:
|
||||
@@ -54,7 +76,9 @@ class OpenAPISchemaGenerator(object):
|
||||
"""Iterate over all the registered endpoints in the API.
|
||||
|
||||
:param rest_framework.request.Request request: used for returning only endpoints available to the given request
|
||||
:return: {path: (view_class, list[(http_method, view_instance)])"""
|
||||
:return: {path: (view_class, list[(http_method, view_instance)])
|
||||
:rtype: dict
|
||||
"""
|
||||
inspector = self._gen.endpoint_inspector_cls(self._gen.patterns, self._gen.urlconf)
|
||||
endpoints = inspector.get_api_endpoints()
|
||||
|
||||
@@ -68,16 +92,21 @@ class OpenAPISchemaGenerator(object):
|
||||
return {path: (view_cls[path], methods) for path, methods in view_paths.items()}
|
||||
|
||||
def get_operation_keys(self, subpath, method, view):
|
||||
"""
|
||||
Return a list of keys that should be used to layout a link within
|
||||
the schema document.
|
||||
"""Return a list of keys that should be used to group an operation within the specification.
|
||||
|
||||
/users/ ("users", "list"), ("users", "create")
|
||||
/users/{pk}/ ("users", "read"), ("users", "update"), ("users", "delete")
|
||||
/users/enabled/ ("users", "enabled") # custom viewset list action
|
||||
/users/{pk}/star/ ("users", "star") # custom viewset detail action
|
||||
/users/{pk}/groups/ ("users", "groups", "list"), ("users", "groups", "create")
|
||||
/users/{pk}/groups/{pk}/ ("users", "groups", "read"), ("users", "groups", "update")
|
||||
::
|
||||
|
||||
/users/ ("users", "list"), ("users", "create")
|
||||
/users/{pk}/ ("users", "read"), ("users", "update"), ("users", "delete")
|
||||
/users/enabled/ ("users", "enabled") # custom viewset list action
|
||||
/users/{pk}/star/ ("users", "star") # custom viewset detail action
|
||||
/users/{pk}/groups/ ("users", "groups", "list"), ("users", "groups", "create")
|
||||
/users/{pk}/groups/{pk}/ ("users", "groups", "read"), ("users", "groups", "update")
|
||||
|
||||
:param str subpath: path to the operation with any common prefix/base path removed
|
||||
:param str method: HTTP method
|
||||
:param view: the view associated with the operation
|
||||
:rtype: tuple
|
||||
"""
|
||||
return self._gen.get_keys(subpath, method, view)
|
||||
|
||||
@@ -86,6 +115,7 @@ class OpenAPISchemaGenerator(object):
|
||||
|
||||
:param dict endpoints: endpoints as returned by get_endpoints
|
||||
:param ReferenceResolver components: resolver/container for Swagger References
|
||||
:rtype: openapi.Paths
|
||||
"""
|
||||
if not endpoints:
|
||||
return openapi.Paths(paths={})
|
||||
@@ -112,6 +142,13 @@ class OpenAPISchemaGenerator(object):
|
||||
return openapi.Paths(paths=paths)
|
||||
|
||||
def get_overrides(self, view, method):
|
||||
"""Get overrides specified for a given operation.
|
||||
|
||||
:param view: the view associated with the operation
|
||||
:param str method: HTTP method
|
||||
:return: a dictionary containing any overrides set by :func:`@swagger_auto_schema <.swagger_auto_schema>`
|
||||
:rtype: dict
|
||||
"""
|
||||
method = method.lower()
|
||||
action = getattr(view, 'action', method)
|
||||
action_method = getattr(view, action, None)
|
||||
@@ -126,7 +163,8 @@ class OpenAPISchemaGenerator(object):
|
||||
|
||||
:param str path: templated request path
|
||||
:param type view_cls: the view class associated with the path
|
||||
:return list[openapi.Parameter]: path parameters
|
||||
:return: path parameters
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
parameters = []
|
||||
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
|
||||
|
||||
@@ -14,6 +14,12 @@ from .utils import serializer_field_to_swagger, no_body, is_list_view
|
||||
|
||||
|
||||
def force_serializer_instance(serializer):
|
||||
"""Force `serializer` into a ``Serializer`` instance. If it is not a ``Serializer`` class or instance, raises
|
||||
an assertion error.
|
||||
|
||||
:param serializer: serializer class or instance
|
||||
:return: serializer instance
|
||||
"""
|
||||
if inspect.isclass(serializer):
|
||||
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
|
||||
return serializer()
|
||||
@@ -25,12 +31,12 @@ def force_serializer_instance(serializer):
|
||||
|
||||
class SwaggerAutoSchema(object):
|
||||
def __init__(self, view, path, method, overrides, components):
|
||||
"""Inspector class responsible for providing Operation definitions given a
|
||||
"""Inspector class responsible for providing :class:`.Operation` definitions given a
|
||||
|
||||
:param view: the view associated with this endpoint
|
||||
:param str path: the path component of the operation URL
|
||||
:param str method: the http method of the operation
|
||||
:param dict overrides: manual overrides as passed to @swagger_auto_schema
|
||||
:param dict overrides: manual overrides as passed to :func:`@swagger_auto_schema <.swagger_auto_schema>`
|
||||
:param openapi.ReferenceResolver components: referenceable components
|
||||
"""
|
||||
super(SwaggerAutoSchema, self).__init__()
|
||||
@@ -43,19 +49,18 @@ class SwaggerAutoSchema(object):
|
||||
self._sch.view = view
|
||||
|
||||
def get_operation(self, operation_keys):
|
||||
"""Get an Operation for the given API endpoint (path, method).
|
||||
"""Get an :class:`.Operation` for the given API endpoint (path, method).
|
||||
This includes query, body parameters and response schemas.
|
||||
|
||||
:param tuple[str] operation_keys: an array of keys describing the hierarchical layout of this view in the API;
|
||||
e.g. ('snippets', 'list'), ('snippets', 'retrieve'), etc.
|
||||
:return: the resulting Operation object
|
||||
e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
|
||||
:rtype: openapi.Operation
|
||||
"""
|
||||
consumes = self.get_consumes()
|
||||
|
||||
body = self.get_request_body_parameters(consumes)
|
||||
query = self.get_query_parameters()
|
||||
parameters = body + query
|
||||
|
||||
parameters = [param for param in parameters if param is not None]
|
||||
parameters = self.add_manual_parameters(parameters)
|
||||
|
||||
@@ -73,13 +78,14 @@ class SwaggerAutoSchema(object):
|
||||
)
|
||||
|
||||
def get_request_body_parameters(self, consumes):
|
||||
"""Return the request body parameters for this view.
|
||||
"""Return the request body parameters for this view. |br|
|
||||
This is either:
|
||||
- a list with a single object Parameter with a Schema derived from the request serializer
|
||||
- a list of primitive Parameters parsed as form data
|
||||
|
||||
:param list[str] consumes: a list of MIME types this request accepts as body
|
||||
:return: a (potentially empty) list of openapi.Parameter in: either `body` or `formData`
|
||||
- a list with a single object Parameter with a :class:`.Schema` derived from the request serializer
|
||||
- a list of primitive Parameters parsed as form data
|
||||
|
||||
:param list[str] consumes: a list of accepted MIME types as returned by :meth:`.get_consumes`
|
||||
:return: a (potentially empty) list of :class:`.Parameter`\ s either ``in: body`` or ``in: formData``
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
# only PUT, PATCH or POST can have a request body
|
||||
@@ -106,8 +112,7 @@ class SwaggerAutoSchema(object):
|
||||
def get_request_serializer(self):
|
||||
"""Return the request serializer (used for parsing the request payload) for this endpoint.
|
||||
|
||||
:return: the request serializer
|
||||
:rtype: serializers.BaseSerializer
|
||||
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
|
||||
"""
|
||||
body_override = self.overrides.get('request_body', None)
|
||||
|
||||
@@ -123,9 +128,9 @@ class SwaggerAutoSchema(object):
|
||||
return self.view.get_serializer()
|
||||
|
||||
def get_request_form_parameters(self, serializer):
|
||||
"""Given a Serializer, return a list of in: formData Parameters.
|
||||
"""Given a Serializer, return a list of ``in: formData`` :class:`.Parameter`\ s.
|
||||
|
||||
:param serializer: the view's request serialzier
|
||||
:param serializer: the view's request serializer as returned by :meth:`.get_request_serializer`
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = getattr(serializer, 'fields', {})
|
||||
@@ -136,18 +141,18 @@ class SwaggerAutoSchema(object):
|
||||
]
|
||||
|
||||
def get_request_body_schema(self, serializer):
|
||||
"""Return the Schema for a given request's body data. Only applies to PUT, PATCH and POST requests.
|
||||
"""Return the :class:`.Schema` for a given request's body data. Only applies to PUT, PATCH and POST requests.
|
||||
|
||||
:param serializers.BaseSerializer serializer: the view's request serialzier
|
||||
:return: the request body schema
|
||||
:param serializer: the view's request serializer as returned by :meth:`.get_request_serializer`
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
return self.serializer_to_schema(serializer)
|
||||
|
||||
def make_body_parameter(self, schema):
|
||||
"""Given a Schema object, create an in: body Parameter.
|
||||
"""Given a :class:`.Schema` object, create an ``in: body`` :class:`.Parameter`.
|
||||
|
||||
:param openapi.Schema schema: the request body schema
|
||||
:rtype: openapi.Parameter
|
||||
"""
|
||||
return openapi.Parameter(name='data', in_=openapi.IN_BODY, required=True, schema=schema)
|
||||
|
||||
@@ -172,9 +177,10 @@ class SwaggerAutoSchema(object):
|
||||
return list(parameters.values())
|
||||
|
||||
def get_responses(self):
|
||||
"""Get the possible responses for this view as a swagger Responses object.
|
||||
"""Get the possible responses for this view as a swagger :class:`.Responses` object.
|
||||
|
||||
:return: the documented responses
|
||||
:rtype: openapi.Responses
|
||||
"""
|
||||
response_serializers = self.get_response_serializers()
|
||||
return openapi.Responses(
|
||||
@@ -182,9 +188,10 @@ class SwaggerAutoSchema(object):
|
||||
)
|
||||
|
||||
def get_paged_response_schema(self, response_schema):
|
||||
"""Add appropriate paging fields to a response Schema.
|
||||
"""Add appropriate paging fields to a response :class:`.Schema`.
|
||||
|
||||
:param openapi.Schema response_schema: the response schema that must be paged.
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
assert response_schema.type == openapi.TYPE_ARRAY, "array return expected for paged response"
|
||||
paged_schema = openapi.Schema(
|
||||
@@ -201,6 +208,10 @@ class SwaggerAutoSchema(object):
|
||||
return paged_schema
|
||||
|
||||
def get_default_responses(self):
|
||||
"""Get the default responses determined for this view from the request serializer and request method.
|
||||
|
||||
:type: dict[str, openapi.Schema]
|
||||
"""
|
||||
method = self.method.lower()
|
||||
|
||||
default_status = status.HTTP_200_OK
|
||||
@@ -227,9 +238,11 @@ class SwaggerAutoSchema(object):
|
||||
def get_response_serializers(self):
|
||||
"""Return the response codes that this view is expected to return, and the serializer for each response body.
|
||||
The return value should be a dict where the keys are possible status codes, and values are either strings,
|
||||
`Serializer` or `openapi.Response` objects.
|
||||
``Serializer``\ s, :class:`.Schema`, :class:`.SchemaRef` or :class:`.Response` objects. See
|
||||
:func:`@swagger_auto_schema <.swagger_auto_schema>` for more details.
|
||||
|
||||
:return dict: the response serializers
|
||||
:return: the response serializers
|
||||
:rtype: dict
|
||||
"""
|
||||
manual_responses = self.overrides.get('responses', None) or {}
|
||||
manual_responses = OrderedDict((str(sc), resp) for sc, resp in manual_responses.items())
|
||||
@@ -242,10 +255,11 @@ class SwaggerAutoSchema(object):
|
||||
return responses
|
||||
|
||||
def get_response_schemas(self, response_serializers):
|
||||
"""Return the `openapi.Response` objects calculated for this view.
|
||||
"""Return the :class:`.openapi.Response` objects calculated for this view.
|
||||
|
||||
:param dict response_serializers: result of get_response_serializers
|
||||
:return dict[str, openapi.Response]: a dictionary of status code to Response object
|
||||
:param dict response_serializers: response serializers as returned by :meth:`.get_response_serializers`
|
||||
:return: a dictionary of status code to :class:`.Response` object
|
||||
:rtype: dict[str, openapi.Response]
|
||||
"""
|
||||
responses = {}
|
||||
for sc, serializer in response_serializers.items():
|
||||
@@ -277,10 +291,15 @@ class SwaggerAutoSchema(object):
|
||||
def get_query_parameters(self):
|
||||
"""Return the query parameters accepted by this view.
|
||||
|
||||
:rtype: list[openapi.Parameter]"""
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
return self.get_filter_parameters() + self.get_pagination_parameters()
|
||||
|
||||
def should_filter(self):
|
||||
"""Determine whether filter backend parameters should be included for this request.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if not getattr(self.view, 'filter_backends', None):
|
||||
return False
|
||||
|
||||
@@ -318,6 +337,10 @@ class SwaggerAutoSchema(object):
|
||||
return fields
|
||||
|
||||
def should_page(self):
|
||||
"""Determine whether paging parameters and structure should be added to this operation's request and response.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if not hasattr(self.view, 'paginator'):
|
||||
return False
|
||||
|
||||
@@ -344,7 +367,8 @@ class SwaggerAutoSchema(object):
|
||||
def get_pagination_parameters(self):
|
||||
"""Return the parameters added to the view by its paginator.
|
||||
|
||||
:rtype: list[openapi.Parameter]"""
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_page():
|
||||
return []
|
||||
|
||||
@@ -372,7 +396,7 @@ class SwaggerAutoSchema(object):
|
||||
return media_types[:1]
|
||||
|
||||
def serializer_to_schema(self, serializer):
|
||||
"""Convert a DRF Serializer instance to an openapi.Schema.
|
||||
"""Convert a DRF Serializer instance to an :class:`.openapi.Schema`.
|
||||
|
||||
:param serializers.BaseSerializer serializer:
|
||||
:rtype: openapi.Schema
|
||||
@@ -381,7 +405,7 @@ class SwaggerAutoSchema(object):
|
||||
return serializer_field_to_swagger(serializer, openapi.Schema, definitions)
|
||||
|
||||
def field_to_parameter(self, field, name, in_):
|
||||
"""Convert a DRF serializer Field to a swagger Parameter object.
|
||||
"""Convert a DRF serializer Field to a swagger :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:param str name: the name of the parameter
|
||||
@@ -391,7 +415,7 @@ class SwaggerAutoSchema(object):
|
||||
return serializer_field_to_swagger(field, openapi.Parameter, name=name, in_=in_)
|
||||
|
||||
def coreapi_field_to_parameter(self, field):
|
||||
"""Convert an instance of `coreapi.Field` to a swagger Parameter object.
|
||||
"""Convert an instance of `coreapi.Field` to a swagger :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:rtype: openapi.Parameter
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
from django.http import HttpResponse
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
|
||||
from .codecs import _OpenAPICodec
|
||||
from .errors import SwaggerValidationError
|
||||
|
||||
|
||||
class SwaggerExceptionMiddleware(MiddlewareMixin):
|
||||
class SwaggerExceptionMiddleware(object):
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
return self.get_response(request)
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
if isinstance(exception, SwaggerValidationError):
|
||||
err = {'errors': {exception.validator_name: str(exception)}}
|
||||
|
||||
+197
-64
@@ -5,42 +5,43 @@ from coreapi.compat import urlparse
|
||||
from future.utils import raise_from
|
||||
from inflection import camelize
|
||||
|
||||
TYPE_OBJECT = "object"
|
||||
TYPE_STRING = "string"
|
||||
TYPE_NUMBER = "number"
|
||||
TYPE_INTEGER = "integer"
|
||||
TYPE_BOOLEAN = "boolean"
|
||||
TYPE_ARRAY = "array"
|
||||
TYPE_FILE = "file"
|
||||
|
||||
TYPE_OBJECT = "object" #:
|
||||
TYPE_STRING = "string" #:
|
||||
TYPE_NUMBER = "number" #:
|
||||
TYPE_INTEGER = "integer" #:
|
||||
TYPE_BOOLEAN = "boolean" #:
|
||||
TYPE_ARRAY = "array" #:
|
||||
TYPE_FILE = "file" #:
|
||||
|
||||
# officially supported by Swagger 2.0 spec
|
||||
FORMAT_DATE = "date"
|
||||
FORMAT_DATETIME = "date-time"
|
||||
FORMAT_PASSWORD = "password"
|
||||
FORMAT_BINARY = "binary"
|
||||
FORMAT_BASE64 = "bytes"
|
||||
FORMAT_FLOAT = "float"
|
||||
FORMAT_DOUBLE = "double"
|
||||
FORMAT_INT32 = "int32"
|
||||
FORMAT_INT64 = "int64"
|
||||
FORMAT_DATE = "date" #:
|
||||
FORMAT_DATETIME = "date-time" #:
|
||||
FORMAT_PASSWORD = "password" #:
|
||||
FORMAT_BINARY = "binary" #:
|
||||
FORMAT_BASE64 = "bytes" #:
|
||||
FORMAT_FLOAT = "float" #:
|
||||
FORMAT_DOUBLE = "double" #:
|
||||
FORMAT_INT32 = "int32" #:
|
||||
FORMAT_INT64 = "int64" #:
|
||||
|
||||
# defined in JSON-schema
|
||||
FORMAT_EMAIL = "email"
|
||||
FORMAT_IPV4 = "ipv4"
|
||||
FORMAT_IPV6 = "ipv6"
|
||||
FORMAT_URI = "uri"
|
||||
FORMAT_EMAIL = "email" #:
|
||||
FORMAT_IPV4 = "ipv4" #:
|
||||
FORMAT_IPV6 = "ipv6" #:
|
||||
FORMAT_URI = "uri" #:
|
||||
|
||||
# pulled out of my ass
|
||||
FORMAT_UUID = "uuid"
|
||||
FORMAT_SLUG = "slug"
|
||||
FORMAT_UUID = "uuid" #:
|
||||
FORMAT_SLUG = "slug" #:
|
||||
|
||||
IN_BODY = 'body'
|
||||
IN_PATH = 'path'
|
||||
IN_QUERY = 'query'
|
||||
IN_FORM = 'formData'
|
||||
IN_HEADER = 'header'
|
||||
IN_BODY = 'body' #:
|
||||
IN_PATH = 'path' #:
|
||||
IN_QUERY = 'query' #:
|
||||
IN_FORM = 'formData' #:
|
||||
IN_HEADER = 'header' #:
|
||||
|
||||
SCHEMA_DEFINITIONS = 'definitions'
|
||||
SCHEMA_DEFINITIONS = 'definitions' #:
|
||||
|
||||
|
||||
def make_swagger_name(attribute_name):
|
||||
@@ -48,7 +49,7 @@ def make_swagger_name(attribute_name):
|
||||
Convert a python variable name into a Swagger spec attribute name.
|
||||
|
||||
In particular,
|
||||
* if name starts with x_, return "x-{camelCase}"
|
||||
* if name starts with x\_, return "x-{camelCase}"
|
||||
* if name is 'ref', return "$ref"
|
||||
* else return the name converted to camelCase, with trailing underscores stripped
|
||||
|
||||
@@ -63,6 +64,10 @@ def make_swagger_name(attribute_name):
|
||||
|
||||
|
||||
class SwaggerDict(OrderedDict):
|
||||
"""A particular type of OrderedDict, which maps all attribute accesses to dict lookups using
|
||||
:func:`.make_swagger_name`. Used as a base class for all Swagger helper models.
|
||||
"""
|
||||
|
||||
def __init__(self, **attrs):
|
||||
super(SwaggerDict, self).__init__()
|
||||
self._extras__ = attrs
|
||||
@@ -109,15 +114,15 @@ class SwaggerDict(OrderedDict):
|
||||
|
||||
|
||||
class Contact(SwaggerDict):
|
||||
"""Swagger Contact object
|
||||
At least one of the following fields is required:
|
||||
|
||||
:param str name: contact name
|
||||
:param str url: contact url
|
||||
:param str email: contact e-mail
|
||||
"""
|
||||
|
||||
def __init__(self, name=None, url=None, email=None, **extra):
|
||||
"""Swagger Contact object
|
||||
|
||||
At least one of the following fields is required:
|
||||
|
||||
:param str name: contact name
|
||||
:param str url: contact url
|
||||
:param str email: contact e-mail
|
||||
"""
|
||||
super(Contact, self).__init__(**extra)
|
||||
if name is None and url is None and email is None:
|
||||
raise AssertionError("one of name, url or email is requires for Swagger Contact object")
|
||||
@@ -128,13 +133,12 @@ class Contact(SwaggerDict):
|
||||
|
||||
|
||||
class License(SwaggerDict):
|
||||
"""Swagger License object
|
||||
|
||||
:param str name: Requird. License name
|
||||
:param str url: link to detailed license information
|
||||
"""
|
||||
|
||||
def __init__(self, name, url=None, **extra):
|
||||
"""Swagger License object
|
||||
|
||||
:param str name: Required. License name
|
||||
:param str url: link to detailed license information
|
||||
"""
|
||||
super(License, self).__init__(**extra)
|
||||
if name is None:
|
||||
raise AssertionError("name is required for Swagger License object")
|
||||
@@ -144,18 +148,17 @@ class License(SwaggerDict):
|
||||
|
||||
|
||||
class Info(SwaggerDict):
|
||||
"""Swagger Info object
|
||||
|
||||
:param str title: Required. API title.
|
||||
:param str default_version: Required. API version string (not to be confused with Swagger spec version)
|
||||
:param str description: API description; markdown supported
|
||||
:param str terms_of_service: API terms of service; should be a URL
|
||||
:param Contact contact: contact object
|
||||
:param License license: license object
|
||||
"""
|
||||
|
||||
def __init__(self, title, default_version, description=None, terms_of_service=None, contact=None, license=None,
|
||||
**extra):
|
||||
"""Swagger Info object
|
||||
|
||||
:param str title: Required. API title.
|
||||
:param str default_version: Required. API version string (not to be confused with Swagger spec version)
|
||||
:param str description: API description; markdown supported
|
||||
:param str terms_of_service: API terms of service; should be a URL
|
||||
:param Contact contact: contact object
|
||||
:param License license: license object
|
||||
"""
|
||||
super(Info, self).__init__(**extra)
|
||||
if title is None or default_version is None:
|
||||
raise AssertionError("title and version are required for Swagger info object")
|
||||
@@ -174,6 +177,14 @@ class Info(SwaggerDict):
|
||||
|
||||
class Swagger(SwaggerDict):
|
||||
def __init__(self, info=None, _url=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 _version: version string to override Info
|
||||
:param .Paths paths: paths object
|
||||
:param dict[str,.Schema] definitions: named models
|
||||
"""
|
||||
super(Swagger, self).__init__(**extra)
|
||||
self.swagger = '2.0'
|
||||
self.info = info
|
||||
@@ -194,6 +205,10 @@ class Swagger(SwaggerDict):
|
||||
|
||||
class Paths(SwaggerDict):
|
||||
def __init__(self, paths, **extra):
|
||||
"""A listing of all the paths in the API.
|
||||
|
||||
:param dict[str,.PathItem] paths:
|
||||
"""
|
||||
super(Paths, self).__init__(**extra)
|
||||
for path, path_obj in paths.items():
|
||||
assert path.startswith("/")
|
||||
@@ -205,14 +220,25 @@ class Paths(SwaggerDict):
|
||||
class PathItem(SwaggerDict):
|
||||
def __init__(self, get=None, put=None, post=None, delete=None, options=None,
|
||||
head=None, patch=None, parameters=None, **extra):
|
||||
"""Information about a single path
|
||||
|
||||
:param .Operation get: operation for GET
|
||||
:param .Operation put: operation for PUT
|
||||
:param .Operation post: operation for POST
|
||||
:param .Operation delete: operation for DELETE
|
||||
:param .Operation options: operation for OPTIONS
|
||||
:param .Operation head: operation for HEAD
|
||||
:param .Operation patch: operation for PATCH
|
||||
:param list[.Parameter] parameters: parameters that apply to all operations
|
||||
"""
|
||||
super(PathItem, self).__init__(**extra)
|
||||
self.get = get
|
||||
self.put = put
|
||||
self.head = head
|
||||
self.post = post
|
||||
self.put = put
|
||||
self.patch = patch
|
||||
self.delete = delete
|
||||
self.options = options
|
||||
self.head = head
|
||||
self.patch = patch
|
||||
self.parameters = parameters
|
||||
self._insert_extras__()
|
||||
|
||||
@@ -220,6 +246,16 @@ class PathItem(SwaggerDict):
|
||||
class Operation(SwaggerDict):
|
||||
def __init__(self, operation_id, responses, parameters=None, consumes=None,
|
||||
produces=None, description=None, tags=None, **extra):
|
||||
"""Information about an API operation (path + http method combination)
|
||||
|
||||
:param str operation_id: operation ID, should be unique across all operations
|
||||
:param .Responses responses: responses returned
|
||||
:param list[.Parameter] parameters: parameters accepted
|
||||
:param list[str] consumes: content types accepted
|
||||
:param list[str] produces: content types produced
|
||||
:param str description: operation description
|
||||
:param list[str] tags: operation tags
|
||||
"""
|
||||
super(Operation, self).__init__(**extra)
|
||||
self.operation_id = operation_id
|
||||
self.description = description
|
||||
@@ -233,6 +269,14 @@ class Operation(SwaggerDict):
|
||||
|
||||
class Items(SwaggerDict):
|
||||
def __init__(self, type=None, format=None, enum=None, pattern=None, items=None, **extra):
|
||||
"""Used when defining an array :class:`.Parameter` to describe the array elements.
|
||||
|
||||
:param str type: type of the array elements; must not be ``object``
|
||||
:param str format: value format, see OpenAPI spec
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param .Items items: only valid if `type` is ``array``
|
||||
"""
|
||||
super(Items, self).__init__(**extra)
|
||||
self.type = type
|
||||
self.format = format
|
||||
@@ -245,6 +289,20 @@ class Items(SwaggerDict):
|
||||
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):
|
||||
"""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.
|
||||
|
||||
:param str name: parameter name
|
||||
:param str in_: parameter location
|
||||
:param str description: parameter description
|
||||
:param bool required: whether the parameter is required for the operation
|
||||
:param .Schema,.SchemaRef schema: required if `in_` is ``body``
|
||||
:param str type: parameter type; required if `in_` is not ``body``; must not be ``object``
|
||||
:param str format: value format, see OpenAPI spec
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param .Items items: only valid if `type` is ``array``
|
||||
"""
|
||||
super(Parameter, self).__init__(**extra)
|
||||
if (not schema and not type) or (schema and type):
|
||||
raise AssertionError("either schema or type are required for Parameter object!")
|
||||
@@ -266,11 +324,23 @@ class Schema(SwaggerDict):
|
||||
|
||||
def __init__(self, description=None, required=None, type=None, properties=None, additional_properties=None,
|
||||
format=None, enum=None, pattern=None, items=None, **extra):
|
||||
"""Describes a complex object accepted as parameter or returned as a response.
|
||||
|
||||
:param description: schema description
|
||||
:param list[str] required: list of requried property names
|
||||
:param str type: value type; required
|
||||
:param list[.Schema,.SchemaRef] properties: object properties; required if `type` is ``object``
|
||||
:param bool,.Schema,.SchemaRef additional_properties: allow wildcard properties not listed in `properties`
|
||||
:param str format: value format, see OpenAPI spec
|
||||
:param list enum: restrict possible values
|
||||
:param str pattern: pattern if type is ``string``
|
||||
:param .Schema,.SchemaRef items: only valid if `type` is ``array``
|
||||
"""
|
||||
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!")
|
||||
"the `requires` attribute of schema must be an array of required properties, not a boolean!")
|
||||
self.description = description
|
||||
self.required = required
|
||||
self.type = type
|
||||
@@ -285,6 +355,14 @@ class Schema(SwaggerDict):
|
||||
|
||||
class _Ref(SwaggerDict):
|
||||
def __init__(self, resolver, name, scope, expected_type):
|
||||
"""Base class for all reference types. A reference object has only one property, ``$ref``, which must be a JSON
|
||||
reference to a valid object in the specification, e.g. ``#/definitions/Article`` to refer to an article model.
|
||||
|
||||
:param .ReferenceResolver resolver: component resolver which must contain the referneced object
|
||||
:param str name: referenced object name, e.g. "Article"
|
||||
:param str scope: reference scope, e.g. "definitions"
|
||||
:param type[.SwaggerDict] expected_type: the expected type that will be asserted on the object found in resolver
|
||||
"""
|
||||
super(_Ref, self).__init__()
|
||||
assert not type(self) == _Ref, "do not instantiate _Ref directly"
|
||||
ref_name = "#/{scope}/{name}".format(scope=scope, name=name)
|
||||
@@ -304,9 +382,9 @@ class _Ref(SwaggerDict):
|
||||
|
||||
class SchemaRef(_Ref):
|
||||
def __init__(self, resolver, schema_name):
|
||||
"""Add a reference to a named Schema defined in the #/definitions/ object.
|
||||
"""Adds a reference to a named Schema defined in the ``#/definitions/`` object.
|
||||
|
||||
:param ReferenceResolver resolver: component resolver which must contain the definition
|
||||
:param .ReferenceResolver resolver: component resolver which must contain the definition
|
||||
:param str schema_name: schema name
|
||||
"""
|
||||
assert SCHEMA_DEFINITIONS in resolver.scopes
|
||||
@@ -318,6 +396,11 @@ Schema.OR_REF = (Schema, SchemaRef)
|
||||
|
||||
class Responses(SwaggerDict):
|
||||
def __init__(self, responses, default=None, **extra):
|
||||
"""Describes the expected responses of an :class:`.Operation`.
|
||||
|
||||
:param dict[(str,int),.Response] responses: mapping of status code to response definition
|
||||
:param .Response default: description of the response structure to expect if another status code is returned
|
||||
"""
|
||||
super(Responses, self).__init__(**extra)
|
||||
for status, response in responses.items():
|
||||
if response is not None:
|
||||
@@ -328,6 +411,12 @@ class Responses(SwaggerDict):
|
||||
|
||||
class Response(SwaggerDict):
|
||||
def __init__(self, description, schema=None, examples=None, **extra):
|
||||
"""Describes the structure of an operation's response.
|
||||
|
||||
:param str description: response description
|
||||
:param .Schema,.SchemaRef schema: sturcture of the response body
|
||||
:param dict examples: example bodies mapped by mime type
|
||||
"""
|
||||
super(Response, self).__init__(**extra)
|
||||
self.description = description
|
||||
self.schema = schema
|
||||
@@ -340,14 +429,20 @@ class ReferenceResolver(object):
|
||||
Provides support and checks for different refernce scopes, e.g. 'definitions'.
|
||||
|
||||
For example:
|
||||
> components = ReferenceResolver('definitions', 'parameters')
|
||||
> definitions = ReferenceResolver.with_scope('definitions')
|
||||
> definitions.set('Article', Schema(...))
|
||||
> print(components)
|
||||
{'definitions': OrderedDict([('Article', Schema(...)]), 'parameters': OrderedDict()}
|
||||
|
||||
::
|
||||
|
||||
> components = ReferenceResolver('definitions', 'parameters')
|
||||
> definitions = ReferenceResolver.with_scope('definitions')
|
||||
> definitions.set('Article', Schema(...))
|
||||
> print(components)
|
||||
{'definitions': OrderedDict([('Article', Schema(...)]), 'parameters': OrderedDict()}
|
||||
"""
|
||||
|
||||
def __init__(self, *scopes):
|
||||
"""
|
||||
:param str scopes: an enumeration of the valid scopes this resolver will contain
|
||||
"""
|
||||
self._objects = OrderedDict()
|
||||
self._force_scope = None
|
||||
for scope in scopes:
|
||||
@@ -355,6 +450,12 @@ class ReferenceResolver(object):
|
||||
self._objects[scope] = OrderedDict()
|
||||
|
||||
def with_scope(self, scope):
|
||||
"""Return a new :class:`.ReferenceResolver` whose scope is defaulted and forced to `scope`.
|
||||
|
||||
:param str scope: target scope, must be in this resolver's `scopes`
|
||||
:return: the bound resolver
|
||||
:rtype: .ReferenceResolver
|
||||
"""
|
||||
assert scope in self.scopes, "unknown scope %s" % scope
|
||||
ret = ReferenceResolver()
|
||||
ret._objects = self._objects
|
||||
@@ -369,12 +470,24 @@ class ReferenceResolver(object):
|
||||
return real_scope
|
||||
|
||||
def set(self, name, obj, scope=None):
|
||||
"""Set an object in the given scope, raise an error if it already exists.
|
||||
|
||||
:param str name: reference name
|
||||
:param obj: referenced object
|
||||
:param str scope: reference scope
|
||||
"""
|
||||
scope = self._check_scope(scope)
|
||||
assert obj is not None, "referenced objects cannot be None/null"
|
||||
assert name not in self._objects[scope], "#/%s/%s already exists" % (scope, name)
|
||||
self._objects[scope][name] = obj
|
||||
|
||||
def setdefault(self, name, maker, scope=None):
|
||||
"""Set an object in the given scope only if it does not exist.
|
||||
|
||||
:param str name: reference name
|
||||
:param callable maker: object factory, called only if necessary
|
||||
:param str scope: reference scope
|
||||
"""
|
||||
scope = self._check_scope(scope)
|
||||
assert callable(maker), "setdefault expects a callable, not %s" % type(maker).__name__
|
||||
ret = self.getdefault(name, None, scope)
|
||||
@@ -386,15 +499,35 @@ class ReferenceResolver(object):
|
||||
return ret
|
||||
|
||||
def get(self, name, scope=None):
|
||||
"""Get an object from the given scope, raise an error if it does not exist.
|
||||
|
||||
:param str name: reference name
|
||||
:param str scope: reference scope
|
||||
:return: the object
|
||||
"""
|
||||
scope = self._check_scope(scope)
|
||||
assert name in self._objects[scope], "#/%s/%s is not defined" % (scope, name)
|
||||
return self._objects[scope][name]
|
||||
|
||||
def getdefault(self, name, default=None, scope=None):
|
||||
"""Get an object from the given scope or a default value if it does not exist.
|
||||
|
||||
:param str name: reference name
|
||||
:param default: the default value
|
||||
:param str scope: reference scope
|
||||
:return: the object or `default`
|
||||
"""
|
||||
scope = self._check_scope(scope)
|
||||
return self._objects[scope].get(name, default)
|
||||
|
||||
def has(self, name, scope=None):
|
||||
"""Check if an object exists in the given scope.
|
||||
|
||||
:param str name: reference name
|
||||
:param str scope: reference scope
|
||||
:return: True if the object exists
|
||||
:rtype: bool
|
||||
"""
|
||||
scope = self._check_scope(scope)
|
||||
return name in self._objects[scope]
|
||||
|
||||
|
||||
@@ -7,8 +7,9 @@ from .codecs import OpenAPICodecJson, VALIDATORS, OpenAPICodecYaml
|
||||
|
||||
|
||||
class _SpecRenderer(BaseRenderer):
|
||||
"""Base class for text renderers. Handles encoding and validation."""
|
||||
charset = None
|
||||
validators = ['flex', 'ssv']
|
||||
validators = ['ssv', 'flex']
|
||||
codec_class = None
|
||||
|
||||
@classmethod
|
||||
@@ -23,24 +24,28 @@ class _SpecRenderer(BaseRenderer):
|
||||
|
||||
|
||||
class OpenAPIRenderer(_SpecRenderer):
|
||||
"""Renders the schema as a JSON document with the ``application/openapi+json`` specific mime type."""
|
||||
media_type = 'application/openapi+json'
|
||||
format = 'openapi'
|
||||
codec_class = OpenAPICodecJson
|
||||
|
||||
|
||||
class SwaggerJSONRenderer(_SpecRenderer):
|
||||
"""Renders the schema as a JSON document with the generic ``application/json`` mime type."""
|
||||
media_type = 'application/json'
|
||||
format = '.json'
|
||||
codec_class = OpenAPICodecJson
|
||||
|
||||
|
||||
class SwaggerYAMLRenderer(_SpecRenderer):
|
||||
"""Renders the schema as a YAML document."""
|
||||
media_type = 'application/yaml'
|
||||
format = '.yaml'
|
||||
codec_class = OpenAPICodecYaml
|
||||
|
||||
|
||||
class _UIRenderer(BaseRenderer):
|
||||
"""Base class for web UI renderers. Handles loading an passing settings to the appropriate template."""
|
||||
media_type = 'text/html'
|
||||
charset = 'utf-8'
|
||||
template = ''
|
||||
@@ -98,10 +103,16 @@ class _UIRenderer(BaseRenderer):
|
||||
|
||||
|
||||
class SwaggerUIRenderer(_UIRenderer):
|
||||
"""Renders a swagger-ui web interface for schema browisng.
|
||||
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
|
||||
"""
|
||||
template = 'drf-swagger/swagger-ui.html'
|
||||
format = 'swagger'
|
||||
|
||||
|
||||
class ReDocRenderer(_UIRenderer):
|
||||
"""Renders a ReDoc web interface for schema browisng.
|
||||
Also requires :class:`.OpenAPIRenderer` as an available renderer on the same view.
|
||||
"""
|
||||
template = 'drf-swagger/redoc.html'
|
||||
format = 'redoc'
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
<!-- HTML for static distribution bundle build -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Swagger UI</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
|
||||
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body {
|
||||
margin:0;
|
||||
background: #fafafa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 20 20" id="unlocked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="locked">
|
||||
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="close">
|
||||
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow">
|
||||
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 20 20" id="large-arrow-down">
|
||||
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
|
||||
</symbol>
|
||||
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="jump-to">
|
||||
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="expand">
|
||||
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
|
||||
</symbol>
|
||||
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="./swagger-ui-bundle.js"> </script>
|
||||
<script src="./swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
|
||||
// Build a system
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "http://petstore.swagger.io/v2/swagger.json",
|
||||
dom_id: '#swagger-ui',
|
||||
deepLinking: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
@@ -8,17 +8,24 @@ from rest_framework.mixins import RetrieveModelMixin, DestroyModelMixin, UpdateM
|
||||
from . import openapi
|
||||
from .errors import SwaggerGenerationError
|
||||
|
||||
#: used to forcibly remove the body of a request via :func:`.swagger_auto_schema`
|
||||
no_body = object()
|
||||
|
||||
|
||||
def is_list_view(path, method, view):
|
||||
"""Return True if the given path/method appears to represent a list view (as opposed to a detail/instance view)."""
|
||||
# for ViewSets, it could be the default 'list' view, or a list_route
|
||||
"""Check if the given path/method appears to represent a list view (as opposed to a detail/instance view).
|
||||
|
||||
:param str path: view path
|
||||
:param str method: http method
|
||||
:param APIView view: target view
|
||||
:rtype: bool
|
||||
"""
|
||||
# for ViewSets, it could be the default 'list' action, or a list_route
|
||||
action = getattr(view, 'action', '')
|
||||
method = getattr(view, action, None)
|
||||
detail = getattr(method, 'detail', None)
|
||||
suffix = getattr(view, 'suffix', None)
|
||||
if action == 'list' or detail is False or suffix == 'List':
|
||||
if action in ('list', 'create') or detail is False or suffix == 'List':
|
||||
return True
|
||||
|
||||
if action in ('retrieve', 'update', 'partial_update', 'destroy') or detail is True or suffix == 'Instance':
|
||||
@@ -34,12 +41,54 @@ def is_list_view(path, method, view):
|
||||
if path_components and '{' in path_components[-1]:
|
||||
return False
|
||||
|
||||
# otherwise assume it's a list route
|
||||
# otherwise assume it's a list view
|
||||
return True
|
||||
|
||||
|
||||
def swagger_auto_schema(method=None, methods=None, auto_schema=None, request_body=None, manual_parameters=None,
|
||||
operation_description=None, responses=None):
|
||||
"""Decorate a view method to customize the :class:`.Operation` object generated from it.
|
||||
|
||||
`method` and `methods` are mutually exclusive and must only be present when decorating a view method that accepts
|
||||
more than one HTTP request method.
|
||||
|
||||
The `auto_schema` and `operation_description` arguments take precendence over view- or method-level values.
|
||||
|
||||
:param str method: for multi-method views, the http method the options should apply to
|
||||
:param list[str] methods: for multi-method views, the http methods the options should apply to
|
||||
:param .SwaggerAutoSchema auto_schema: custom class to use for generating the Operation object
|
||||
:param .Schema,.SchemaRef,.Serializer request_body: custom request body, or :data:`.no_body`. The value given here
|
||||
will be used as the ``schema`` property of a :class:`.Parameter` with ``in: 'body'``.
|
||||
|
||||
A Schema or SchemaRef is not valid if this request consumes form-data, because ``form`` and ``body`` parameters
|
||||
are mutually exclusive in an :class:`.Operation`. If you need to set custom ``form`` parameters, you can use
|
||||
the `manual_parameters` argument.
|
||||
|
||||
If a ``Serializer`` class or instance is given, it will be automatically converted into a :class:`.Schema`
|
||||
used as a ``body`` :class:`.Parameter`, or into a list of ``form`` :class:`.Parameter`\ s, as appropriate.
|
||||
|
||||
:param list[.Parameter] manual_parameters: a list of manual parameters to override the automatically generated ones
|
||||
|
||||
:class:`.Parameter`\ s are identified by their (``name``, ``in``) combination, and any parameters given
|
||||
here will fully override automatically generated parameters if they collide.
|
||||
|
||||
It is an error to supply ``form`` parameters when the request does not consume form-data.
|
||||
|
||||
:param str operation_description: operation description override
|
||||
:param dict[str,(.Schema,.SchemaRef,.Response,str,Serializer)] responses: a dict of documented manual responses
|
||||
keyed on response status code. If no success (``2xx``) response is given, one will automatically be
|
||||
generated from the request body and http method. If any ``2xx`` response is given the automatic response is
|
||||
suppressed.
|
||||
|
||||
* if a plain string is given as value, a :class:`.Response` with no body and that string as its description
|
||||
will be generated
|
||||
* if a :class:`.Schema`, :class:`.SchemaRef` is given, a :class:`.Response` with the schema as its body and
|
||||
an empty description will be generated
|
||||
* a ``Serializer`` class or instance will be converted into a :class:`.Schema` and treated as above
|
||||
* a :class:`.Response` object will be used as-is; however if its ``schema`` attribute is a ``Serializer``,
|
||||
it will automatically be converted into a :class:`.Schema`
|
||||
|
||||
"""
|
||||
def decorator(view_method):
|
||||
data = {
|
||||
'auto_schema': auto_schema,
|
||||
@@ -98,11 +147,12 @@ def serializer_field_to_swagger(field, swagger_object_type, definitions=None, **
|
||||
"""Convert a drf Serializer or Field instance into a Swagger object.
|
||||
|
||||
:param rest_framework.serializers.Field field: the source field
|
||||
:param type swagger_object_type: should be one of Schema, Parameter, Items
|
||||
:param drf_swagger.openapi.ReferenceResolver definitions: used to serialize Schemas by reference
|
||||
:param type[openapi.SwaggerDict] swagger_object_type: should be one of Schema, Parameter, Items
|
||||
:param .ReferenceResolver definitions: used to serialize Schemas by reference
|
||||
:param kwargs: extra attributes for constructing the object;
|
||||
if swagger_object_type is Parameter, `name` and `in_` should be provided
|
||||
:return Swagger,Parameter,Items: the swagger object
|
||||
if swagger_object_type is Parameter, ``name`` and ``in_`` should be provided
|
||||
:return: the swagger object
|
||||
:rtype: openapi.Parameter, openapi.Items, openapi.Schema
|
||||
"""
|
||||
assert swagger_object_type in (openapi.Schema, openapi.Parameter, openapi.Items)
|
||||
assert not isinstance(field, openapi.SwaggerDict), "passed field is already a SwaggerDict object"
|
||||
@@ -241,6 +291,12 @@ def serializer_field_to_swagger(field, swagger_object_type, definitions=None, **
|
||||
|
||||
|
||||
def find_regex(regex_field):
|
||||
"""Given a ``Field``, look for a ``RegexValidator`` and try to extract its pattern and return it as a string.
|
||||
|
||||
:param serializers.Field regex_field: the field instance
|
||||
:return: the extracted pattern, or ``None``
|
||||
:rtype: str
|
||||
"""
|
||||
regex_validator = None
|
||||
for validator in regex_field.validators:
|
||||
if isinstance(validator, RegexValidator):
|
||||
|
||||
@@ -53,16 +53,17 @@ def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, v
|
||||
"""
|
||||
Create a SchemaView class with default renderers and generators.
|
||||
|
||||
:param drf_swagger.openapi.Info info: Required. Swagger API Info object
|
||||
:param .Info info: Required. Swagger API Info object
|
||||
:param str url: API base url; if left blank will be deduced from the location the view is served at
|
||||
:param str patterns: passed to SchemaGenerator
|
||||
:param str urlconf: passed to SchemaGenerator
|
||||
: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 list validators: a list of validator names to apply on the generated schema; allowed values are `flex`, `ssv`
|
||||
:param type generator_class: schema generator class to use; should be a subclass of OpenAPISchemaGenerator
|
||||
: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
|
||||
:param tuple permission_classes: permission classes for the schema view itself
|
||||
:return: SchemaView class
|
||||
:rtype: type[.SchemaView]
|
||||
"""
|
||||
_public = public
|
||||
_generator_class = generator_class
|
||||
@@ -101,7 +102,8 @@ def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, v
|
||||
cache_kwargs = cache_kwargs or {}
|
||||
view = cls.as_view(**initkwargs)
|
||||
if cache_timeout != 0:
|
||||
view = vary_on_headers('Cookie', 'Authorization', 'Accept')(view)
|
||||
if not public:
|
||||
view = vary_on_headers('Cookie', 'Authorization')(view)
|
||||
view = cache_page(cache_timeout, **cache_kwargs)(view)
|
||||
view = deferred_never_cache(view) # disable in-browser caching
|
||||
elif cache_kwargs:
|
||||
@@ -126,7 +128,7 @@ def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, v
|
||||
Instantiate this view with a Web UI renderer, optionally wrapped with cache_page.
|
||||
See https://docs.djangoproject.com/en/1.11/topics/cache/.
|
||||
|
||||
:param str renderer: UI renderer; allowed values are `swagger`, `redoc`
|
||||
:param str renderer: UI renderer; allowed values are ``swagger``, ``redoc``
|
||||
:param int cache_timeout: same as cache_page; set to 0 for no cache
|
||||
:param dict cache_kwargs: dictionary of kwargs to be passed to cache_page
|
||||
:return: a view instance
|
||||
|
||||
Reference in New Issue
Block a user