Rename to drf-yasg
drf-swagger was already taken
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
# coding=utf-8
|
||||
from pkg_resources import get_distribution, DistributionNotFound
|
||||
|
||||
__author__ = """Cristi V."""
|
||||
__email__ = 'cristi@cvjd.me'
|
||||
|
||||
try:
|
||||
__version__ = get_distribution(__name__).version
|
||||
except DistributionNotFound: # pragma: no cover
|
||||
# package is not installed
|
||||
pass
|
||||
@@ -0,0 +1,78 @@
|
||||
from django.conf import settings
|
||||
from rest_framework.settings import perform_import
|
||||
|
||||
SWAGGER_DEFAULTS = {
|
||||
'USE_SESSION_AUTH': True,
|
||||
'SECURITY_DEFINITIONS': {
|
||||
'basic': {
|
||||
'type': 'basic'
|
||||
}
|
||||
},
|
||||
'LOGIN_URL': getattr(settings, 'LOGIN_URL', None),
|
||||
'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None),
|
||||
'VALIDATOR_URL': '',
|
||||
|
||||
'OPERATIONS_SORTER': None,
|
||||
'TAGS_SORTER': None,
|
||||
'DOC_EXPANSION': 'list',
|
||||
'DEEP_LINKING': False,
|
||||
'SHOW_EXTENSIONS': True,
|
||||
'DEFAULT_MODEL_RENDERING': 'model',
|
||||
'DEFAULT_MODEL_DEPTH': 2,
|
||||
}
|
||||
|
||||
REDOC_DEFAULTS = {
|
||||
'LAZY_RENDERING': True,
|
||||
'HIDE_HOSTNAME': False,
|
||||
'EXPAND_RESPONSES': 'all',
|
||||
'PATH_IN_MIDDLE': False,
|
||||
}
|
||||
|
||||
IMPORT_STRINGS = []
|
||||
|
||||
|
||||
class AppSettings(object):
|
||||
"""
|
||||
Stolen from Django Rest Framework, removed caching for easier testing
|
||||
"""
|
||||
|
||||
def __init__(self, user_settings, defaults, import_strings=None):
|
||||
self._user_settings = user_settings
|
||||
self.defaults = defaults
|
||||
self.import_strings = import_strings or []
|
||||
|
||||
@property
|
||||
def user_settings(self):
|
||||
return getattr(settings, self._user_settings, {})
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr not in self.defaults:
|
||||
raise AttributeError("Invalid setting: '%s'" % attr) # pragma: no cover
|
||||
|
||||
try:
|
||||
# Check if present in user settings
|
||||
val = self.user_settings[attr]
|
||||
except KeyError:
|
||||
# Fall back to defaults
|
||||
val = self.defaults[attr]
|
||||
|
||||
# Coerce import strings into classes
|
||||
if attr in self.import_strings:
|
||||
val = perform_import(val, attr)
|
||||
|
||||
return val
|
||||
|
||||
|
||||
#:
|
||||
swagger_settings = AppSettings(
|
||||
user_settings='SWAGGER_SETTINGS',
|
||||
defaults=SWAGGER_DEFAULTS,
|
||||
import_strings=IMPORT_STRINGS,
|
||||
)
|
||||
|
||||
#:
|
||||
redoc_settings = AppSettings(
|
||||
user_settings='REDOC_SETTINGS',
|
||||
defaults=REDOC_DEFAULTS,
|
||||
import_strings=IMPORT_STRINGS,
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
import copy
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
|
||||
from coreapi.compat import force_bytes
|
||||
from future.utils import raise_from
|
||||
from ruamel import yaml
|
||||
|
||||
from . import openapi
|
||||
from .app_settings import swagger_settings
|
||||
from .errors import SwaggerValidationError
|
||||
|
||||
|
||||
def _validate_flex(spec, codec):
|
||||
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)
|
||||
|
||||
|
||||
def _validate_swagger_spec_validator(spec, codec):
|
||||
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)
|
||||
|
||||
|
||||
#:
|
||||
VALIDATORS = {
|
||||
'flex': _validate_flex,
|
||||
'ssv': _validate_swagger_spec_validator,
|
||||
}
|
||||
|
||||
|
||||
class _OpenAPICodec(object):
|
||||
media_type = None
|
||||
|
||||
def __init__(self, validators):
|
||||
self._validators = validators
|
||||
|
||||
@property
|
||||
def validators(self):
|
||||
"""List of validator names to apply"""
|
||||
return self._validators
|
||||
|
||||
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')
|
||||
|
||||
spec = self.generate_swagger_object(document)
|
||||
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)
|
||||
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.
|
||||
|
||||
: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
|
||||
return swagger
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@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.
|
||||
|
||||
To use yaml.safe_dump(), you need the following.
|
||||
"""
|
||||
tag = u'tag:yaml.org,2002:map'
|
||||
value = []
|
||||
node = yaml.MappingNode(tag, value, flow_style=flow_style)
|
||||
if dump.alias_key is not None:
|
||||
dump.represented_objects[dump.alias_key] = node
|
||||
best_style = True
|
||||
if hasattr(mapping, 'items'):
|
||||
mapping = mapping.items()
|
||||
for item_key, item_value in mapping:
|
||||
node_key = dump.represent_data(item_key)
|
||||
node_value = dump.represent_data(item_value)
|
||||
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
|
||||
best_style = False
|
||||
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
|
||||
best_style = False
|
||||
value.append((node_key, node_value))
|
||||
if flow_style is None:
|
||||
if dump.default_flow_style is not None:
|
||||
node.flow_style = dump.default_flow_style
|
||||
else:
|
||||
node.flow_style = best_style
|
||||
return node
|
||||
|
||||
|
||||
SaneYamlDumper.add_representer(OrderedDict, SaneYamlDumper.represent_odict)
|
||||
SaneYamlDumper.add_multi_representer(OrderedDict, SaneYamlDumper.represent_odict)
|
||||
|
||||
|
||||
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')
|
||||
@@ -0,0 +1,14 @@
|
||||
class SwaggerError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class SwaggerValidationError(SwaggerError):
|
||||
def __init__(self, msg, validator_name, spec, source_codec, *args):
|
||||
super(SwaggerValidationError, self).__init__(msg, *args)
|
||||
self.validator_name = validator_name
|
||||
self.spec = spec
|
||||
self.source_codec = source_codec
|
||||
|
||||
|
||||
class SwaggerGenerationError(SwaggerError):
|
||||
pass
|
||||
@@ -0,0 +1,204 @@
|
||||
from collections import defaultdict, OrderedDict
|
||||
|
||||
import django.db.models
|
||||
import uritemplate
|
||||
from coreapi.compat import force_text
|
||||
from rest_framework.schemas.generators import SchemaGenerator
|
||||
from rest_framework.schemas.inspectors import get_pk_description
|
||||
|
||||
from . import openapi
|
||||
from .inspectors import SwaggerAutoSchema
|
||||
from .openapi import ReferenceResolver
|
||||
|
||||
|
||||
class OpenAPISchemaGenerator(object):
|
||||
"""
|
||||
This class iterates over all registered API endpoints and returns an appropriate OpenAPI 2.0 compliant schema.
|
||||
Method implementations shamelessly stolen and adapted from rest_framework SchemaGenerator.
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
def get_schema(self, request=None, public=False):
|
||||
"""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)
|
||||
|
||||
url = self._gen.url
|
||||
if not url and request is not None:
|
||||
url = request.build_absolute_uri()
|
||||
|
||||
return openapi.Swagger(
|
||||
info=self.info, paths=paths,
|
||||
_url=url, _version=self.version, **dict(components)
|
||||
)
|
||||
|
||||
def create_view(self, callback, method, request=None):
|
||||
"""Create a view instance from a view callback as registered in urlpatterns.
|
||||
|
||||
:param callable callback: view callback registered in urlpatterns
|
||||
:param 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:
|
||||
# decorated function based view must have its decorator information passed on to the re-instantiated view
|
||||
for method, _ in overrides.items():
|
||||
view_method = getattr(view, method, None)
|
||||
if view_method is not None: # pragma: no cover
|
||||
setattr(view_method.__func__, 'swagger_auto_schema', overrides)
|
||||
return view
|
||||
|
||||
def get_endpoints(self, request=None):
|
||||
"""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)])
|
||||
:rtype: dict
|
||||
"""
|
||||
inspector = self._gen.endpoint_inspector_cls(self._gen.patterns, self._gen.urlconf)
|
||||
endpoints = inspector.get_api_endpoints()
|
||||
|
||||
view_paths = defaultdict(list)
|
||||
view_cls = {}
|
||||
for path, method, callback in endpoints:
|
||||
view = self.create_view(callback, method, request)
|
||||
path = self._gen.coerce_path(path, method, view)
|
||||
view_paths[path].append((method, view))
|
||||
view_cls[path] = callback.cls
|
||||
return {path: (view_cls[path], methods) for path, methods in view_paths.items()}
|
||||
|
||||
def get_operation_keys(self, subpath, method, view):
|
||||
"""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")
|
||||
|
||||
: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)
|
||||
|
||||
def get_paths(self, endpoints, components):
|
||||
"""Generate the Swagger Paths for the API from the given endpoints.
|
||||
|
||||
:param dict endpoints: endpoints as returned by get_endpoints
|
||||
:param ReferenceResolver components: resolver/container for Swagger References
|
||||
:rtype: openapi.Paths
|
||||
"""
|
||||
if not endpoints:
|
||||
return openapi.Paths(paths={})
|
||||
|
||||
prefix = self._gen.determine_path_prefix(endpoints.keys())
|
||||
paths = OrderedDict()
|
||||
|
||||
default_schema_cls = SwaggerAutoSchema
|
||||
for path, (view_cls, methods) in sorted(endpoints.items()):
|
||||
path_parameters = self.get_path_parameters(path, view_cls)
|
||||
operations = {}
|
||||
for method, view in methods:
|
||||
if not self._gen.has_view_permissions(path, method, view):
|
||||
continue
|
||||
|
||||
operation_keys = self.get_operation_keys(path[len(prefix):], method, view)
|
||||
overrides = self.get_overrides(view, method)
|
||||
auto_schema_cls = overrides.get('auto_schema', default_schema_cls)
|
||||
schema = auto_schema_cls(view, path, method, overrides, components)
|
||||
operations[method.lower()] = schema.get_operation(operation_keys)
|
||||
|
||||
if operations:
|
||||
paths[path] = openapi.PathItem(parameters=path_parameters, **operations)
|
||||
|
||||
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)
|
||||
overrides = getattr(action_method, 'swagger_auto_schema', {})
|
||||
if method in overrides:
|
||||
overrides = overrides[method]
|
||||
|
||||
return overrides
|
||||
|
||||
def get_path_parameters(self, path, view_cls):
|
||||
"""Return a list of Parameter instances corresponding to any templated path variables.
|
||||
|
||||
:param str path: templated request path
|
||||
:param type view_cls: the view class associated with the path
|
||||
:return: path parameters
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
parameters = []
|
||||
model = getattr(getattr(view_cls, 'queryset', None), 'model', None)
|
||||
|
||||
for variable in uritemplate.variables(path):
|
||||
pattern = None
|
||||
type = openapi.TYPE_STRING
|
||||
description = None
|
||||
if model is not None:
|
||||
# Attempt to infer a field description if possible.
|
||||
try:
|
||||
model_field = model._meta.get_field(variable)
|
||||
except Exception: # pragma: no cover
|
||||
model_field = None
|
||||
|
||||
if model_field is not None and model_field.help_text:
|
||||
description = force_text(model_field.help_text)
|
||||
elif model_field is not None and model_field.primary_key:
|
||||
description = get_pk_description(model, model_field)
|
||||
|
||||
if hasattr(view_cls, 'lookup_value_regex') and getattr(view_cls, 'lookup_field', None) == variable:
|
||||
pattern = view_cls.lookup_value_regex
|
||||
elif isinstance(model_field, django.db.models.AutoField):
|
||||
type = openapi.TYPE_INTEGER
|
||||
|
||||
field = openapi.Parameter(
|
||||
name=variable,
|
||||
required=True,
|
||||
in_=openapi.IN_PATH,
|
||||
type=type,
|
||||
pattern=pattern,
|
||||
description=description,
|
||||
)
|
||||
parameters.append(field)
|
||||
|
||||
return parameters
|
||||
@@ -0,0 +1,441 @@
|
||||
import inspect
|
||||
from collections import OrderedDict
|
||||
|
||||
import coreschema
|
||||
from rest_framework import serializers, status
|
||||
from rest_framework.request import is_form_media_type
|
||||
from rest_framework.schemas import AutoSchema
|
||||
from rest_framework.status import is_success
|
||||
from rest_framework.viewsets import GenericViewSet
|
||||
|
||||
from . import openapi
|
||||
from .errors import SwaggerGenerationError
|
||||
from .utils import serializer_field_to_swagger, no_body, is_list_view
|
||||
|
||||
|
||||
def force_serializer_instance(serializer):
|
||||
"""Force `serializer` into a ``Serializer`` instance. If it is not a ``Serializer`` class or instance, raises
|
||||
an assertion error.
|
||||
|
||||
:param serializer: serializer class or instance
|
||||
:return: serializer instance
|
||||
"""
|
||||
if inspect.isclass(serializer):
|
||||
assert issubclass(serializer, serializers.BaseSerializer), "Serializer required, not %s" % serializer.__name__
|
||||
return serializer()
|
||||
|
||||
assert isinstance(serializer, serializers.BaseSerializer), \
|
||||
"Serializer class or instance required, not %s" % type(serializer).__name__
|
||||
return serializer
|
||||
|
||||
|
||||
class SwaggerAutoSchema(object):
|
||||
def __init__(self, view, path, method, overrides, components):
|
||||
"""Inspector class responsible for providing :class:`.Operation` definitions given a
|
||||
|
||||
:param view: the view associated with this endpoint
|
||||
:param str path: the path component of the operation URL
|
||||
:param str method: the http method of the operation
|
||||
:param dict overrides: manual overrides as passed to :func:`@swagger_auto_schema <.swagger_auto_schema>`
|
||||
:param openapi.ReferenceResolver components: referenceable components
|
||||
"""
|
||||
super(SwaggerAutoSchema, self).__init__()
|
||||
self._sch = AutoSchema()
|
||||
self.view = view
|
||||
self.path = path
|
||||
self.method = method
|
||||
self.overrides = overrides
|
||||
self.components = components
|
||||
self._sch.view = view
|
||||
|
||||
def get_operation(self, operation_keys):
|
||||
"""Get an :class:`.Operation` for the given API endpoint (path, method).
|
||||
This includes query, body parameters and response schemas.
|
||||
|
||||
:param tuple[str] operation_keys: an array of keys describing the hierarchical layout of this view in the API;
|
||||
e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
|
||||
:rtype: openapi.Operation
|
||||
"""
|
||||
consumes = self.get_consumes()
|
||||
|
||||
body = self.get_request_body_parameters(consumes)
|
||||
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)
|
||||
|
||||
description = self.get_description()
|
||||
|
||||
responses = self.get_responses()
|
||||
|
||||
return openapi.Operation(
|
||||
operation_id='_'.join(operation_keys),
|
||||
description=description,
|
||||
responses=responses,
|
||||
parameters=parameters,
|
||||
consumes=consumes,
|
||||
tags=[operation_keys[0]],
|
||||
)
|
||||
|
||||
def get_request_body_parameters(self, consumes):
|
||||
"""Return the request body parameters for this view. |br|
|
||||
This is either:
|
||||
|
||||
- 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
|
||||
if self.method not in ('PUT', 'PATCH', 'POST'):
|
||||
return []
|
||||
|
||||
serializer = self.get_request_serializer()
|
||||
schema = None
|
||||
if serializer is None:
|
||||
return []
|
||||
|
||||
if isinstance(serializer, openapi.Schema.OR_REF):
|
||||
schema = serializer
|
||||
|
||||
if any(is_form_media_type(encoding) for encoding in consumes):
|
||||
if schema is not None:
|
||||
raise SwaggerGenerationError("form request body cannot be a Schema")
|
||||
return self.get_request_form_parameters(serializer)
|
||||
else:
|
||||
if schema is None:
|
||||
schema = self.get_request_body_schema(serializer)
|
||||
return [self.make_body_parameter(schema)]
|
||||
|
||||
def get_request_serializer(self):
|
||||
"""Return the request serializer (used for parsing the request payload) for this endpoint.
|
||||
|
||||
:return: the request serializer, or one of :class:`.Schema`, :class:`.SchemaRef`, ``None``
|
||||
"""
|
||||
body_override = self.overrides.get('request_body', None)
|
||||
|
||||
if body_override is not None:
|
||||
if body_override is no_body:
|
||||
return None
|
||||
if isinstance(body_override, openapi.Schema.OR_REF):
|
||||
return body_override
|
||||
return force_serializer_instance(body_override)
|
||||
else:
|
||||
if not hasattr(self.view, 'get_serializer'):
|
||||
return None
|
||||
return self.view.get_serializer()
|
||||
|
||||
def get_request_form_parameters(self, serializer):
|
||||
"""Given a Serializer, return a list of ``in: formData`` :class:`.Parameter`\ s.
|
||||
|
||||
:param serializer: the view's request serializer as returned by :meth:`.get_request_serializer`
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = getattr(serializer, 'fields', {})
|
||||
return [
|
||||
self.field_to_parameter(value, key, openapi.IN_FORM)
|
||||
for key, value
|
||||
in fields.items()
|
||||
]
|
||||
|
||||
def get_request_body_schema(self, serializer):
|
||||
"""Return the :class:`.Schema` for a given request's body data. Only applies to PUT, PATCH and POST requests.
|
||||
|
||||
: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 :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)
|
||||
|
||||
def add_manual_parameters(self, parameters):
|
||||
"""Add/replace parameters from the given list of automatically generated request parameters.
|
||||
|
||||
:param list[openapi.Parameter] parameters: genereated parameters
|
||||
:return: modified parameters
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
parameters = OrderedDict(((param.name, param.in_), param) for param in parameters)
|
||||
manual_parameters = self.overrides.get('manual_parameters', None) or []
|
||||
|
||||
if any(param.in_ == openapi.IN_BODY for param in manual_parameters): # pragma: no cover
|
||||
raise SwaggerGenerationError("specify the body parameter as a Schema or Serializer in request_body")
|
||||
if any(param.in_ == openapi.IN_FORM for param in manual_parameters): # pragma: no cover
|
||||
if any(param.in_ == openapi.IN_BODY for param in parameters.values()):
|
||||
raise SwaggerGenerationError("cannot add form parameters when the request has a request schema; "
|
||||
"did you forget to set an appropriate parser class on the view?")
|
||||
|
||||
parameters.update(((param.name, param.in_), param) for param in manual_parameters)
|
||||
return list(parameters.values())
|
||||
|
||||
def get_responses(self):
|
||||
"""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(
|
||||
responses=self.get_response_schemas(response_serializers)
|
||||
)
|
||||
|
||||
def get_paged_response_schema(self, response_schema):
|
||||
"""Add appropriate paging fields to a response :class:`.Schema`.
|
||||
|
||||
:param openapi.Schema response_schema: the response schema that must be paged.
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
assert response_schema.type == openapi.TYPE_ARRAY, "array return expected for paged response"
|
||||
paged_schema = openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties={
|
||||
'count': openapi.Schema(type=openapi.TYPE_INTEGER),
|
||||
'next': openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI),
|
||||
'previous': openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI),
|
||||
'results': response_schema,
|
||||
},
|
||||
required=['count', 'results']
|
||||
)
|
||||
|
||||
return paged_schema
|
||||
|
||||
def get_default_responses(self):
|
||||
"""Get the default responses determined for this view from the request serializer and request method.
|
||||
|
||||
:type: dict[str, openapi.Schema]
|
||||
"""
|
||||
method = self.method.lower()
|
||||
|
||||
default_status = status.HTTP_200_OK
|
||||
default_schema = ''
|
||||
if method == 'post':
|
||||
default_status = status.HTTP_201_CREATED
|
||||
default_schema = self.get_request_serializer()
|
||||
elif method == 'delete':
|
||||
default_status = status.HTTP_204_NO_CONTENT
|
||||
elif method in ('get', 'put', 'patch'):
|
||||
default_schema = self.get_request_serializer()
|
||||
|
||||
default_schema = default_schema or ''
|
||||
if default_schema:
|
||||
if not isinstance(default_schema, openapi.Schema):
|
||||
default_schema = self.serializer_to_schema(default_schema)
|
||||
if is_list_view(self.path, self.method, self.view) and self.method.lower() == 'get':
|
||||
default_schema = openapi.Schema(type=openapi.TYPE_ARRAY, items=default_schema)
|
||||
if self.should_page():
|
||||
default_schema = self.get_paged_response_schema(default_schema)
|
||||
|
||||
return {str(default_status): default_schema}
|
||||
|
||||
def get_response_serializers(self):
|
||||
"""Return the response codes that this view is expected to return, and the serializer for each response body.
|
||||
The return value should be a dict where the keys are possible status codes, and values are either strings,
|
||||
``Serializer``\ s, :class:`.Schema`, :class:`.SchemaRef` or :class:`.Response` objects. See
|
||||
:func:`@swagger_auto_schema <.swagger_auto_schema>` for more details.
|
||||
|
||||
: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())
|
||||
|
||||
responses = {}
|
||||
if not any(is_success(int(sc)) for sc in manual_responses if sc != 'default'):
|
||||
responses = self.get_default_responses()
|
||||
|
||||
responses.update((str(sc), resp) for sc, resp in manual_responses.items())
|
||||
return responses
|
||||
|
||||
def get_response_schemas(self, response_serializers):
|
||||
"""Return the :class:`.openapi.Response` objects calculated for this view.
|
||||
|
||||
: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():
|
||||
if isinstance(serializer, str):
|
||||
response = openapi.Response(
|
||||
description=serializer
|
||||
)
|
||||
elif isinstance(serializer, openapi.Response):
|
||||
response = serializer
|
||||
if not isinstance(response.schema, openapi.Schema.OR_REF):
|
||||
serializer = force_serializer_instance(response.schema)
|
||||
response.schema = self.serializer_to_schema(serializer)
|
||||
elif isinstance(serializer, openapi.Schema.OR_REF):
|
||||
response = openapi.Response(
|
||||
description='',
|
||||
schema=serializer,
|
||||
)
|
||||
else:
|
||||
serializer = force_serializer_instance(serializer)
|
||||
response = openapi.Response(
|
||||
description='',
|
||||
schema=self.serializer_to_schema(serializer),
|
||||
)
|
||||
|
||||
responses[str(sc)] = response
|
||||
|
||||
return responses
|
||||
|
||||
def get_query_parameters(self):
|
||||
"""Return the query parameters accepted by this view.
|
||||
|
||||
: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
|
||||
|
||||
if self.method.lower() not in ["get", "delete"]:
|
||||
return False
|
||||
|
||||
if not isinstance(self.view, GenericViewSet):
|
||||
return True
|
||||
|
||||
return is_list_view(self.path, self.method, self.view)
|
||||
|
||||
def get_filter_backend_parameters(self, filter_backend):
|
||||
"""Get the filter parameters for a single filter backend **instance**.
|
||||
|
||||
:param BaseFilterBackend filter_backend: the filter backend
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = []
|
||||
if hasattr(filter_backend, 'get_schema_fields'):
|
||||
fields = filter_backend.get_schema_fields(self.view)
|
||||
return [self.coreapi_field_to_parameter(field) for field in fields]
|
||||
|
||||
def get_filter_parameters(self):
|
||||
"""Return the parameters added to the view by its filter backends.
|
||||
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_filter():
|
||||
return []
|
||||
|
||||
fields = []
|
||||
for filter_backend in self.view.filter_backends:
|
||||
fields += self.get_filter_backend_parameters(filter_backend())
|
||||
|
||||
return fields
|
||||
|
||||
def should_page(self):
|
||||
"""Determine whether paging parameters and structure should be added to this operation's request and response.
|
||||
|
||||
:rtype: bool
|
||||
"""
|
||||
if not hasattr(self.view, 'paginator'):
|
||||
return False
|
||||
|
||||
if self.view.paginator is None:
|
||||
return False
|
||||
|
||||
if self.method.lower() != 'get':
|
||||
return False
|
||||
|
||||
return is_list_view(self.path, self.method, self.view)
|
||||
|
||||
def get_paginator_parameters(self, paginator):
|
||||
"""Get the pagination parameters for a single paginator **instance**.
|
||||
|
||||
:param BasePagination paginator: the paginator
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
fields = []
|
||||
if hasattr(paginator, 'get_schema_fields'):
|
||||
fields = paginator.get_schema_fields(self.view)
|
||||
|
||||
return [self.coreapi_field_to_parameter(field) for field in fields]
|
||||
|
||||
def get_pagination_parameters(self):
|
||||
"""Return the parameters added to the view by its paginator.
|
||||
|
||||
:rtype: list[openapi.Parameter]
|
||||
"""
|
||||
if not self.should_page():
|
||||
return []
|
||||
|
||||
return self.get_paginator_parameters(self.view.paginator)
|
||||
|
||||
def get_description(self):
|
||||
"""Return an operation description determined as appropriate from the view's method and class docstrings.
|
||||
|
||||
:return: the operation description
|
||||
:rtype: str
|
||||
"""
|
||||
description = self.overrides.get('operation_description', None)
|
||||
if description is None:
|
||||
description = self._sch.get_description(self.path, self.method)
|
||||
return description
|
||||
|
||||
def get_consumes(self):
|
||||
"""Return the MIME types this endpoint can consume.
|
||||
|
||||
:rtype: list[str]
|
||||
"""
|
||||
media_types = [parser.media_type for parser in getattr(self.view, 'parser_classes', [])]
|
||||
if all(is_form_media_type(encoding) for encoding in media_types):
|
||||
return media_types
|
||||
return media_types[:1]
|
||||
|
||||
def serializer_to_schema(self, serializer):
|
||||
"""Convert a DRF Serializer instance to an :class:`.openapi.Schema`.
|
||||
|
||||
:param serializers.BaseSerializer serializer:
|
||||
:rtype: openapi.Schema
|
||||
"""
|
||||
definitions = self.components.with_scope(openapi.SCHEMA_DEFINITIONS)
|
||||
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 :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:param str name: the name of the parameter
|
||||
:param str in_: the location of the parameter, one of the `openapi.IN_*` constants
|
||||
:rtype: openapi.Parameter
|
||||
"""
|
||||
return serializer_field_to_swagger(field, openapi.Parameter, name=name, in_=in_)
|
||||
|
||||
def coreapi_field_to_parameter(self, field):
|
||||
"""Convert an instance of `coreapi.Field` to a swagger :class:`.Parameter` object.
|
||||
|
||||
:param coreapi.Field field:
|
||||
:rtype: openapi.Parameter
|
||||
"""
|
||||
location_to_in = {
|
||||
'query': openapi.IN_QUERY,
|
||||
'path': openapi.IN_PATH,
|
||||
'form': openapi.IN_FORM,
|
||||
'body': openapi.IN_FORM,
|
||||
}
|
||||
coreapi_types = {
|
||||
coreschema.Integer: openapi.TYPE_INTEGER,
|
||||
coreschema.Number: openapi.TYPE_NUMBER,
|
||||
coreschema.String: openapi.TYPE_STRING,
|
||||
coreschema.Boolean: openapi.TYPE_BOOLEAN,
|
||||
}
|
||||
return openapi.Parameter(
|
||||
name=field.name,
|
||||
in_=location_to_in[field.location],
|
||||
type=coreapi_types.get(type(field.schema), openapi.TYPE_STRING),
|
||||
required=field.required,
|
||||
description=field.schema.description,
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
from django.http import HttpResponse
|
||||
|
||||
from .codecs import _OpenAPICodec
|
||||
from .errors import SwaggerValidationError
|
||||
|
||||
|
||||
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)}}
|
||||
codec = exception.source_codec
|
||||
if isinstance(codec, _OpenAPICodec):
|
||||
err = codec.encode_error(err)
|
||||
content_type = codec.media_type
|
||||
return HttpResponse(err, status=500, content_type=content_type)
|
||||
|
||||
return None # pragma: no cover
|
||||
@@ -0,0 +1,556 @@
|
||||
import copy
|
||||
from collections import OrderedDict
|
||||
|
||||
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" #:
|
||||
|
||||
# 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" #:
|
||||
|
||||
# defined in JSON-schema
|
||||
FORMAT_EMAIL = "email" #:
|
||||
FORMAT_IPV4 = "ipv4" #:
|
||||
FORMAT_IPV6 = "ipv6" #:
|
||||
FORMAT_URI = "uri" #:
|
||||
|
||||
# pulled out of my ass
|
||||
FORMAT_UUID = "uuid" #:
|
||||
FORMAT_SLUG = "slug" #:
|
||||
|
||||
IN_BODY = 'body' #:
|
||||
IN_PATH = 'path' #:
|
||||
IN_QUERY = 'query' #:
|
||||
IN_FORM = 'formData' #:
|
||||
IN_HEADER = 'header' #:
|
||||
|
||||
SCHEMA_DEFINITIONS = 'definitions' #:
|
||||
|
||||
|
||||
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 is 'ref', return "$ref"
|
||||
* else return the name converted to camelCase, with trailing underscores stripped
|
||||
|
||||
:param str attribute_name: python attribute name
|
||||
:return: swagger name
|
||||
"""
|
||||
if attribute_name == 'ref':
|
||||
return "$ref"
|
||||
if attribute_name.startswith("x_"):
|
||||
return "x-" + camelize(attribute_name[2:], uppercase_first_letter=False)
|
||||
return camelize(attribute_name.rstrip('_'), uppercase_first_letter=False)
|
||||
|
||||
|
||||
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
|
||||
if type(self) == SwaggerDict:
|
||||
self._insert_extras__()
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
if key.startswith('_'):
|
||||
super(SwaggerDict, self).__setattr__(key, value)
|
||||
return
|
||||
if value is not None:
|
||||
self[make_swagger_name(key)] = value
|
||||
|
||||
def __getattr__(self, item):
|
||||
if item.startswith('_'):
|
||||
raise AttributeError
|
||||
try:
|
||||
return self[make_swagger_name(item)]
|
||||
except KeyError as e:
|
||||
raise_from(AttributeError("object of class " + type(self).__name__ + " has no attribute " + item), e)
|
||||
|
||||
def __delattr__(self, item):
|
||||
if item.startswith('_'):
|
||||
super(SwaggerDict, self).__delattr__(item)
|
||||
return
|
||||
del self[make_swagger_name(item)]
|
||||
|
||||
def _insert_extras__(self):
|
||||
"""
|
||||
From an ordering perspective, it is desired that extra attributes such as vendor extensions stay at the
|
||||
bottom of the object. However, python2.7's OrderdDict craps out if you try to insert into it before calling
|
||||
init. This means that subclasses must call super().__init__ as the first statement of their own __init__,
|
||||
which would result in the extra attributes being added first. For this reason, we defer the insertion of the
|
||||
attributes and require that subclasses call ._insert_extras__ at the end of their __init__ method.
|
||||
"""
|
||||
for attr, val in self._extras__.items():
|
||||
setattr(self, attr, val)
|
||||
|
||||
# noinspection PyArgumentList,PyDefaultArgument
|
||||
def __deepcopy__(self, memodict={}):
|
||||
result = OrderedDict(list(self.items()))
|
||||
result.update(copy.deepcopy(result, memodict))
|
||||
return result
|
||||
|
||||
|
||||
class Contact(SwaggerDict):
|
||||
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")
|
||||
self.name = name
|
||||
self.url = url
|
||||
self.email = email
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
class License(SwaggerDict):
|
||||
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")
|
||||
self.name = name
|
||||
self.url = url
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
class Info(SwaggerDict):
|
||||
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")
|
||||
if contact is not None and not isinstance(contact, Contact):
|
||||
raise AssertionError("contact must be a Contact object")
|
||||
if license is not None and not isinstance(license, License):
|
||||
raise AssertionError("license must be a License object")
|
||||
self.title = title
|
||||
self._default_version = default_version
|
||||
self.description = description
|
||||
self.terms_of_service = terms_of_service
|
||||
self.contact = contact
|
||||
self.license = license
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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
|
||||
self.info.version = _version or info._default_version
|
||||
|
||||
if _url:
|
||||
url = urlparse.urlparse(_url)
|
||||
if url.netloc:
|
||||
self.host = url.netloc
|
||||
if url.scheme:
|
||||
self.schemes = [url.scheme]
|
||||
self.base_path = '/'
|
||||
|
||||
self.paths = paths
|
||||
self.definitions = definitions
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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("/")
|
||||
if path_obj is not None: # pragma: no cover
|
||||
self[path] = path_obj
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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.head = head
|
||||
self.post = post
|
||||
self.put = put
|
||||
self.patch = patch
|
||||
self.delete = delete
|
||||
self.options = options
|
||||
self.parameters = parameters
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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
|
||||
self.parameters = [param for param in parameters if param is not None]
|
||||
self.responses = responses
|
||||
self.consumes = consumes
|
||||
self.produces = produces
|
||||
self.tags = tags
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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
|
||||
self.enum = enum
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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!")
|
||||
self.name = name
|
||||
self.in_ = in_
|
||||
self.description = description
|
||||
self.required = required
|
||||
self.schema = schema
|
||||
self.type = type
|
||||
self.format = format
|
||||
self.enum = enum
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
class Schema(SwaggerDict):
|
||||
OR_REF = ()
|
||||
|
||||
def __init__(self, description=None, required=None, type=None, properties=None, additional_properties=None,
|
||||
format=None, enum=None, pattern=None, items=None, **extra):
|
||||
"""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!")
|
||||
self.description = description
|
||||
self.required = required
|
||||
self.type = type
|
||||
self.properties = properties
|
||||
self.additional_properties = additional_properties
|
||||
self.format = format
|
||||
self.enum = enum
|
||||
self.pattern = pattern
|
||||
self.items = items
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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)
|
||||
obj = resolver.get(name, scope)
|
||||
assert isinstance(obj, expected_type), ref_name + " is a {actual}, not a {expected}" \
|
||||
.format(actual=type(obj).__name__, expected=expected_type.__name__)
|
||||
self.ref = ref_name
|
||||
|
||||
def __setitem__(self, key, value, **kwargs):
|
||||
if key == "$ref":
|
||||
return super(_Ref, self).__setitem__(key, value, **kwargs)
|
||||
raise NotImplementedError("only $ref can be set on Reference objects (not %s)" % key)
|
||||
|
||||
def __delitem__(self, key, **kwargs):
|
||||
raise NotImplementedError("cannot delete property of Reference object")
|
||||
|
||||
|
||||
class SchemaRef(_Ref):
|
||||
def __init__(self, resolver, schema_name):
|
||||
"""Adds a reference to a named Schema defined in the ``#/definitions/`` object.
|
||||
|
||||
:param .ReferenceResolver resolver: component resolver which must contain the definition
|
||||
:param str schema_name: schema name
|
||||
"""
|
||||
assert SCHEMA_DEFINITIONS in resolver.scopes
|
||||
super(SchemaRef, self).__init__(resolver, schema_name, SCHEMA_DEFINITIONS, Schema)
|
||||
|
||||
|
||||
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: # pragma: no cover
|
||||
self[str(status)] = response
|
||||
self.default = default
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
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
|
||||
self.examples = examples
|
||||
self._insert_extras__()
|
||||
|
||||
|
||||
class ReferenceResolver(object):
|
||||
"""A mapping type intended for storing objects pointed at by Swagger Refs.
|
||||
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()}
|
||||
"""
|
||||
|
||||
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:
|
||||
assert isinstance(scope, str), "scope names must be strings"
|
||||
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
|
||||
ret._force_scope = scope
|
||||
return ret
|
||||
|
||||
def _check_scope(self, scope):
|
||||
real_scope = self._force_scope or scope
|
||||
if scope is not None:
|
||||
assert not self._force_scope or scope == self._force_scope, "cannot overrride forced scope"
|
||||
assert real_scope and real_scope in self._objects, "invalid scope %s" % scope
|
||||
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)
|
||||
if ret is None:
|
||||
ret = maker()
|
||||
assert ret is not None, "maker returned None; referenced objects cannot be None/null"
|
||||
self.set(name, ret, scope)
|
||||
|
||||
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]
|
||||
|
||||
def __iter__(self):
|
||||
if self._force_scope:
|
||||
return iter(self._objects[self._force_scope])
|
||||
return iter(self._objects)
|
||||
|
||||
@property
|
||||
def scopes(self):
|
||||
if self._force_scope:
|
||||
return [self._force_scope]
|
||||
return list(self._objects.keys())
|
||||
|
||||
# act as mapping
|
||||
def keys(self):
|
||||
if self._force_scope:
|
||||
return self._objects[self._force_scope].keys()
|
||||
return self._objects.keys()
|
||||
|
||||
def __getitem__(self, item):
|
||||
if self._force_scope:
|
||||
return self._objects[self._force_scope][item]
|
||||
return self._objects[item]
|
||||
|
||||
def __str__(self):
|
||||
return str(dict(self))
|
||||
@@ -0,0 +1,118 @@
|
||||
from django.shortcuts import render, resolve_url
|
||||
from rest_framework.renderers import BaseRenderer
|
||||
from rest_framework.utils import json
|
||||
|
||||
from .app_settings import swagger_settings, redoc_settings
|
||||
from .codecs import OpenAPICodecJson, VALIDATORS, OpenAPICodecYaml
|
||||
|
||||
|
||||
class _SpecRenderer(BaseRenderer):
|
||||
"""Base class for text renderers. Handles encoding and validation."""
|
||||
charset = None
|
||||
validators = ['ssv', 'flex']
|
||||
codec_class = None
|
||||
|
||||
@classmethod
|
||||
def with_validators(cls, validators):
|
||||
assert all(vld in VALIDATORS for vld in validators), "allowed validators are" + ", ".join(VALIDATORS)
|
||||
return type(cls.__name__, (cls,), {'validators': validators})
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
assert self.codec_class, "must override codec_class"
|
||||
codec = self.codec_class(self.validators)
|
||||
return codec.encode(data)
|
||||
|
||||
|
||||
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 = ''
|
||||
|
||||
def render(self, swagger, accepted_media_type=None, renderer_context=None):
|
||||
self.set_context(renderer_context, swagger)
|
||||
return render(
|
||||
renderer_context['request'],
|
||||
self.template,
|
||||
renderer_context
|
||||
)
|
||||
|
||||
def set_context(self, renderer_context, swagger):
|
||||
renderer_context['title'] = swagger.info.title
|
||||
renderer_context['version'] = swagger.info.version
|
||||
renderer_context['swagger_settings'] = json.dumps(self.get_swagger_ui_settings())
|
||||
renderer_context['redoc_settings'] = json.dumps(self.get_redoc_settings())
|
||||
renderer_context['USE_SESSION_AUTH'] = swagger_settings.USE_SESSION_AUTH
|
||||
renderer_context.update(self.get_auth_urls())
|
||||
|
||||
def get_auth_urls(self):
|
||||
urls = {}
|
||||
if swagger_settings.LOGIN_URL is not None:
|
||||
urls['LOGIN_URL'] = resolve_url(swagger_settings.LOGIN_URL)
|
||||
if swagger_settings.LOGOUT_URL is not None:
|
||||
urls['LOGOUT_URL'] = resolve_url(swagger_settings.LOGOUT_URL)
|
||||
|
||||
return urls
|
||||
|
||||
def get_swagger_ui_settings(self):
|
||||
data = {
|
||||
'operationsSorter': swagger_settings.OPERATIONS_SORTER,
|
||||
'tagsSorter': swagger_settings.TAGS_SORTER,
|
||||
'docExpansion': swagger_settings.DOC_EXPANSION,
|
||||
'deepLinking': swagger_settings.DEEP_LINKING,
|
||||
'showExtensions': swagger_settings.SHOW_EXTENSIONS,
|
||||
'defaultModelRendering': swagger_settings.DEFAULT_MODEL_RENDERING,
|
||||
'defaultModelExpandDepth': swagger_settings.DEFAULT_MODEL_DEPTH,
|
||||
}
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
if swagger_settings.VALIDATOR_URL != '':
|
||||
data['validatorUrl'] = swagger_settings.VALIDATOR_URL
|
||||
|
||||
return data
|
||||
|
||||
def get_redoc_settings(self):
|
||||
data = {
|
||||
'lazyRendering': redoc_settings.LAZY_RENDERING,
|
||||
'hideHostname': redoc_settings.HIDE_HOSTNAME,
|
||||
'expandResponses': redoc_settings.EXPAND_RESPONSES,
|
||||
'pathInMiddle': redoc_settings.PATH_IN_MIDDLE,
|
||||
}
|
||||
|
||||
return data
|
||||
|
||||
|
||||
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-yasg/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-yasg/redoc.html'
|
||||
format = 'redoc'
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
// insertion-query v1.0.3 (2016-01-20)
|
||||
// license:MIT
|
||||
// Zbyszek Tenerowicz <naugtur@gmail.com> (http://naugtur.pl/)
|
||||
var insertionQ=function(){"use strict";function a(a,b){var d,e="insQ_"+g++,f=function(a){(a.animationName===e||a[i]===e)&&(c(a.target)||b(a.target))};d=document.createElement("style"),d.innerHTML="@"+j+"keyframes "+e+" { from { outline: 1px solid transparent } to { outline: 0px solid transparent } }\n"+a+" { animation-duration: 0.001s; animation-name: "+e+"; "+j+"animation-duration: 0.001s; "+j+"animation-name: "+e+"; } ",document.head.appendChild(d);var h=setTimeout(function(){document.addEventListener("animationstart",f,!1),document.addEventListener("MSAnimationStart",f,!1),document.addEventListener("webkitAnimationStart",f,!1)},n.timeout);return{destroy:function(){clearTimeout(h),d&&(document.head.removeChild(d),d=null),document.removeEventListener("animationstart",f),document.removeEventListener("MSAnimationStart",f),document.removeEventListener("webkitAnimationStart",f)}}}function b(a){a.QinsQ=!0}function c(a){return n.strictlyNew&&a.QinsQ===!0}function d(a){return c(a.parentNode)?a:d(a.parentNode)}function e(a){for(b(a),a=a.firstChild;a;a=a.nextSibling)void 0!==a&&1===a.nodeType&&e(a)}function f(f,g){var h=[],i=function(){var a;return function(){clearTimeout(a),a=setTimeout(function(){h.forEach(e),g(h),h=[]},10)}}();return a(f,function(a){if(!c(a)){b(a);var e=d(a);h.indexOf(e)<0&&h.push(e),i()}})}var g=100,h=!1,i="animationName",j="",k="Webkit Moz O ms Khtml".split(" "),l="",m=document.createElement("div"),n={strictlyNew:!0,timeout:20};if(m.style.animationName&&(h=!0),h===!1)for(var o=0;o<k.length;o++)if(void 0!==m.style[k[o]+"AnimationName"]){l=k[o],i=l+"AnimationName",j="-"+l.toLowerCase()+"-",h=!0;break}var p=function(b){return h&&b.match(/[^{}]/)?(n.strictlyNew&&e(document.body),{every:function(c){return a(b,c)},summary:function(a){return f(b,a)}}):!1};return p.config=function(a){for(var b in a)a.hasOwnProperty(b)&&(n[b]=a[b])},p}();"undefined"!=typeof module&&"undefined"!=typeof module.exports&&(module.exports=insertionQ);
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,22 @@
|
||||
# Swagger UI Dist
|
||||
[](http://badge.fury.io/js/swagger-ui-dist)
|
||||
|
||||
# API
|
||||
|
||||
This module, `swagger-ui-dist`, exposes Swagger-UI's entire dist folder as a dependency-free npm module.
|
||||
Use `swagger-ui` instead, if you'd like to have npm install dependencies for you.
|
||||
|
||||
`SwaggerUIBundle` and `SwaggerUIStandalonePreset` can be imported:
|
||||
```javascript
|
||||
import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist"
|
||||
```
|
||||
|
||||
To get an absolute path to this directory for static file serving, use the exported `getAbsoluteFSPath` method:
|
||||
|
||||
```javascript
|
||||
const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath()
|
||||
|
||||
// then instantiate server that serves files from the swaggerUiAssetPath
|
||||
```
|
||||
|
||||
For anything else, check the [Swagger-UI](https://github.com/swagger-api/swagger-ui) repository.
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* getAbsoluteFSPath
|
||||
* @return {string} When run in NodeJS env, returns the absolute path to the current directory
|
||||
* When run outside of NodeJS, will return an error message
|
||||
*/
|
||||
const getAbsoluteFSPath = function () {
|
||||
// detect whether we are running in a browser or nodejs
|
||||
if (typeof module !== "undefined" && module.exports) {
|
||||
return require("path").resolve(__dirname)
|
||||
}
|
||||
throw new Error('getAbsoluteFSPath can only be called within a Nodejs environment');
|
||||
}
|
||||
|
||||
module.exports = getAbsoluteFSPath
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 445 B |
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
@@ -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>
|
||||
@@ -0,0 +1,17 @@
|
||||
try {
|
||||
module.exports.SwaggerUIBundle = require("./swagger-ui-bundle.js")
|
||||
module.exports.SwaggerUIStandalonePreset = require("./swagger-ui-standalone-preset.js")
|
||||
} catch(e) {
|
||||
// swallow the error if there's a problem loading the assets.
|
||||
// allows this module to support providing the assets for browserish contexts,
|
||||
// without exploding in a Node context.
|
||||
//
|
||||
// see https://github.com/swagger-api/swagger-ui/issues/3291#issuecomment-311195388
|
||||
// for more information.
|
||||
}
|
||||
|
||||
// `absolutePath` and `getAbsoluteFSPath` are both here because at one point,
|
||||
// we documented having one and actually implemented the other.
|
||||
// They were both retained so we don't break anyone's code.
|
||||
module.exports.absolutePath = require("./absolute-path.js")
|
||||
module.exports.getAbsoluteFSPath = require("./absolute-path.js")
|
||||
@@ -0,0 +1,60 @@
|
||||
<!doctype html>
|
||||
<html lang="en-US">
|
||||
<body onload="run()">
|
||||
</body>
|
||||
</html>
|
||||
<script>
|
||||
'use strict';
|
||||
function run () {
|
||||
var oauth2 = window.opener.swaggerUIRedirectOauth2;
|
||||
var sentState = oauth2.state;
|
||||
var redirectUrl = oauth2.redirectUrl;
|
||||
var isValid, qp, arr;
|
||||
|
||||
if (/code|token|error/.test(window.location.hash)) {
|
||||
qp = window.location.hash.substring(1);
|
||||
} else {
|
||||
qp = location.search.substring(1);
|
||||
}
|
||||
|
||||
arr = qp.split("&")
|
||||
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
|
||||
qp = qp ? JSON.parse('{' + arr.join() + '}',
|
||||
function (key, value) {
|
||||
return key === "" ? value : decodeURIComponent(value)
|
||||
}
|
||||
) : {}
|
||||
|
||||
isValid = qp.state === sentState
|
||||
|
||||
if ((
|
||||
oauth2.auth.schema.get("flow") === "accessCode"||
|
||||
oauth2.auth.schema.get("flow") === "authorizationCode"
|
||||
) && !oauth2.auth.code) {
|
||||
if (!isValid) {
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "warning",
|
||||
message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
|
||||
});
|
||||
}
|
||||
|
||||
if (qp.code) {
|
||||
delete oauth2.state;
|
||||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "error",
|
||||
message: "Authorization failed: no accessCode received from the server"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
|
||||
}
|
||||
window.close();
|
||||
}
|
||||
</script>
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":[],"names":[],"mappings":"","file":"swagger-ui.css","sourceRoot":""}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,43 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<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>
|
||||
</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);
|
||||
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,216 @@
|
||||
<!-- HTML for static distribution bundle build -->
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<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" 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;
|
||||
}
|
||||
|
||||
*,
|
||||
*: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>
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" 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"></path>
|
||||
</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"></path>
|
||||
</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"></path>
|
||||
</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"></path>
|
||||
</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"></path>
|
||||
</symbol>
|
||||
|
||||
<symbol viewBox="0 0 24 24" id="expand">
|
||||
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"></path>
|
||||
</symbol>
|
||||
|
||||
</defs>
|
||||
</svg>
|
||||
|
||||
<div id="swagger-ui"></div>
|
||||
<div id="spec-error" class="hidden alert alert-danger"></div>
|
||||
|
||||
<script>
|
||||
"use strict";
|
||||
var currentPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
||||
var specURL = currentPath + '?format=openapi';
|
||||
|
||||
function patchSwaggerUi() {
|
||||
var authWrapper = document.querySelector('.auth-wrapper');
|
||||
var authorizeButton = document.querySelector('.auth-wrapper .authorize');
|
||||
var djangoSessionAuth = document.querySelector('#django-session-auth');
|
||||
if (document.querySelector('.auth-wrapper #django-session-auth')) {
|
||||
console.log("session auth already patched");
|
||||
return;
|
||||
}
|
||||
|
||||
authWrapper.insertBefore(djangoSessionAuth, authorizeButton);
|
||||
djangoSessionAuth.classList.remove("hidden");
|
||||
|
||||
var divider = document.createElement("div");
|
||||
divider.classList.add("divider");
|
||||
authWrapper.insertBefore(divider, authorizeButton);
|
||||
}
|
||||
|
||||
function initSwaggerUi() {
|
||||
var swaggerConfig = {
|
||||
url: specURL,
|
||||
dom_id: '#swagger-ui',
|
||||
displayOperationId: true,
|
||||
displayRequestDuration: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
};
|
||||
|
||||
var swaggerSettings = {};
|
||||
swaggerSettings = {{ swagger_settings | safe }};
|
||||
console.log(swaggerSettings);
|
||||
for (var p in swaggerSettings) {
|
||||
if (swaggerSettings.hasOwnProperty(p)) {
|
||||
swaggerConfig[p] = swaggerSettings[p];
|
||||
}
|
||||
}
|
||||
window.ui = SwaggerUIBundle(swaggerConfig);
|
||||
}
|
||||
|
||||
window.onload = function () {
|
||||
insertionQ('.auth-wrapper .authorize').every(patchSwaggerUi);
|
||||
initSwaggerUi();
|
||||
};
|
||||
</script>
|
||||
|
||||
<script 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>
|
||||
|
||||
<div id="django-session-auth" class="hidden">
|
||||
{% if USE_SESSION_AUTH %}
|
||||
{% csrf_token %}
|
||||
{% if request.user.is_authenticated %}
|
||||
<div class="hello">
|
||||
<span class="django-session">Django</span> <span class="label label-primary">{{ request.user }}</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if request.user.is_authenticated %}
|
||||
<div class='btn authorize'>
|
||||
<a id="auth" class="header__btn" href="{{ LOGOUT_URL }}?next={{ request.path }}" data-sw-translate>
|
||||
Django Logout
|
||||
</a>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class='btn authorize'>
|
||||
<a id="auth" class="header__btn" href="{{ LOGIN_URL }}?next={{ request.path }}" data-sw-translate>
|
||||
Django Login
|
||||
</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,309 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.core.validators import RegexValidator
|
||||
from django.utils.encoding import force_text
|
||||
from rest_framework import serializers
|
||||
from rest_framework.mixins import RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin
|
||||
|
||||
from . 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):
|
||||
"""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 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':
|
||||
# a detail_route is surely not a list route
|
||||
return False
|
||||
|
||||
# for APIView, if it's a detail view it can't also be a list view
|
||||
if isinstance(view, (RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin)):
|
||||
return False
|
||||
|
||||
# if the last component in the path is parameterized it's probably not a list view
|
||||
path_components = path.strip('/').split('/')
|
||||
if path_components and '{' in path_components[-1]:
|
||||
return False
|
||||
|
||||
# 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,
|
||||
'request_body': request_body,
|
||||
'manual_parameters': manual_parameters,
|
||||
'operation_description': operation_description,
|
||||
'responses': responses,
|
||||
}
|
||||
data = {k: v for k, v in data.items() if v is not None}
|
||||
|
||||
bind_to_methods = getattr(view_method, 'bind_to_methods', [])
|
||||
# if the method is actually a function based view
|
||||
view_cls = getattr(view_method, 'cls', None)
|
||||
http_method_names = getattr(view_cls, 'http_method_names', [])
|
||||
if bind_to_methods or http_method_names:
|
||||
# detail_route, list_route or api_view
|
||||
assert bool(http_method_names) != bool(bind_to_methods), "this should never happen"
|
||||
available_methods = http_method_names + bind_to_methods
|
||||
existing_data = getattr(view_method, 'swagger_auto_schema', {})
|
||||
|
||||
if http_method_names:
|
||||
_route = "api_view"
|
||||
else:
|
||||
_route = "detail_route" if view_method.detail else "list_route"
|
||||
|
||||
_methods = methods
|
||||
if len(available_methods) > 1:
|
||||
assert methods or method, \
|
||||
"on multi-method %s, you must specify swagger_auto_schema on a per-method basis " \
|
||||
"using one of the `method` or `methods` arguments" % _route
|
||||
assert bool(methods) != bool(method), "specify either method or methods"
|
||||
if method:
|
||||
_methods = [method.lower()]
|
||||
else:
|
||||
_methods = [mth.lower() for mth in methods]
|
||||
assert not isinstance(_methods, str), "`methods` expects to receive; use `method` for a single arg"
|
||||
assert not any(mth in existing_data for mth in _methods), "method defined multiple times"
|
||||
assert all(mth in available_methods for mth in _methods), "method not bound to %s" % _route
|
||||
|
||||
existing_data.update((mth.lower(), data) for mth in _methods)
|
||||
else:
|
||||
existing_data[available_methods[0]] = data
|
||||
view_method.swagger_auto_schema = existing_data
|
||||
else:
|
||||
assert methods is None, \
|
||||
"the methods argument should only be specified when decorating a detail_route or list_route; you " \
|
||||
"should also ensure that you put the swagger_auto_schema decorator AFTER (above) the _route decorator"
|
||||
view_method.swagger_auto_schema = data
|
||||
|
||||
return view_method
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def serializer_field_to_swagger(field, swagger_object_type, definitions=None, **kwargs):
|
||||
"""Convert a drf Serializer or Field instance into a Swagger object.
|
||||
|
||||
:param rest_framework.serializers.Field field: the source field
|
||||
:param type[openapi.SwaggerDict] swagger_object_type: should be one of Schema, Parameter, Items
|
||||
:param .ReferenceResolver definitions: used to serialize Schemas by reference
|
||||
:param kwargs: extra attributes for constructing the object;
|
||||
if swagger_object_type is Parameter, ``name`` and ``in_`` should be provided
|
||||
:return: the swagger object
|
||||
:rtype: openapi.Parameter, openapi.Items, openapi.Schema
|
||||
"""
|
||||
assert swagger_object_type in (openapi.Schema, openapi.Parameter, openapi.Items)
|
||||
assert not isinstance(field, openapi.SwaggerDict), "passed field is already a SwaggerDict object"
|
||||
title = force_text(field.label) if field.label else None
|
||||
title = title if swagger_object_type == openapi.Schema else None # only Schema has title
|
||||
title = None
|
||||
description = force_text(field.help_text) if field.help_text else None
|
||||
description = description if swagger_object_type != openapi.Items else None # Items has no description either
|
||||
|
||||
def SwaggerType(**instance_kwargs):
|
||||
if swagger_object_type == openapi.Parameter:
|
||||
instance_kwargs['required'] = field.required
|
||||
if swagger_object_type != openapi.Items:
|
||||
default = getattr(field, 'default', serializers.empty)
|
||||
if default is not serializers.empty:
|
||||
instance_kwargs['default'] = default
|
||||
instance_kwargs.update(kwargs)
|
||||
return swagger_object_type(title=title, description=description, **instance_kwargs)
|
||||
|
||||
# arrays in Schema have Schema elements, arrays in Parameter and Items have Items elements
|
||||
ChildSwaggerType = openapi.Schema if swagger_object_type == openapi.Schema else openapi.Items
|
||||
|
||||
# ------ NESTED
|
||||
if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
|
||||
child_schema = serializer_field_to_swagger(field.child, ChildSwaggerType, definitions)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=child_schema,
|
||||
)
|
||||
elif isinstance(field, serializers.Serializer):
|
||||
if swagger_object_type != openapi.Schema:
|
||||
raise SwaggerGenerationError("cannot instantiate nested serializer as " + swagger_object_type.__name__)
|
||||
assert definitions is not None, "ReferenceResolver required when instantiating Schema"
|
||||
|
||||
serializer = field
|
||||
if hasattr(serializer, '__ref_name__'):
|
||||
ref_name = serializer.__ref_name__
|
||||
else:
|
||||
ref_name = type(serializer).__name__
|
||||
if ref_name.endswith('Serializer'):
|
||||
ref_name = ref_name[:-len('Serializer')]
|
||||
|
||||
def make_schema_definition():
|
||||
properties = OrderedDict()
|
||||
required = []
|
||||
for key, value in serializer.fields.items():
|
||||
properties[key] = serializer_field_to_swagger(value, ChildSwaggerType, definitions)
|
||||
if value.read_only:
|
||||
properties[key].read_only = value.read_only
|
||||
if value.required:
|
||||
required.append(key)
|
||||
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties=properties,
|
||||
required=required or None,
|
||||
)
|
||||
|
||||
if not ref_name:
|
||||
return make_schema_definition()
|
||||
|
||||
definitions.setdefault(ref_name, make_schema_definition)
|
||||
return openapi.SchemaRef(definitions, ref_name)
|
||||
elif isinstance(field, serializers.ManyRelatedField):
|
||||
child_schema = serializer_field_to_swagger(field.child_relation, ChildSwaggerType, definitions)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=child_schema,
|
||||
unique_items=True, # is this OK?
|
||||
)
|
||||
elif isinstance(field, serializers.RelatedField):
|
||||
# TODO: infer type for PrimaryKeyRelatedField?
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
# ------ CHOICES
|
||||
elif isinstance(field, serializers.MultipleChoiceField):
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=ChildSwaggerType(
|
||||
type=openapi.TYPE_STRING,
|
||||
enum=list(field.choices.keys())
|
||||
)
|
||||
)
|
||||
elif isinstance(field, serializers.ChoiceField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, enum=list(field.choices.keys()))
|
||||
# ------ BOOL
|
||||
elif isinstance(field, serializers.BooleanField):
|
||||
return SwaggerType(type=openapi.TYPE_BOOLEAN)
|
||||
# ------ NUMERIC
|
||||
elif isinstance(field, (serializers.DecimalField, serializers.FloatField)):
|
||||
# TODO: min_value max_value
|
||||
return SwaggerType(type=openapi.TYPE_NUMBER)
|
||||
elif isinstance(field, serializers.IntegerField):
|
||||
# TODO: min_value max_value
|
||||
return SwaggerType(type=openapi.TYPE_INTEGER)
|
||||
# ------ STRING
|
||||
elif isinstance(field, serializers.EmailField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_EMAIL)
|
||||
elif isinstance(field, serializers.RegexField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, pattern=find_regex(field))
|
||||
elif isinstance(field, serializers.SlugField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_SLUG, pattern=find_regex(field))
|
||||
elif isinstance(field, serializers.URLField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI)
|
||||
elif isinstance(field, serializers.IPAddressField):
|
||||
format = {'ipv4': openapi.FORMAT_IPV4, 'ipv6': openapi.FORMAT_IPV6}.get(field.protocol, None)
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=format)
|
||||
elif isinstance(field, serializers.CharField):
|
||||
# TODO: min_length max_length (for all CharField subclasses above too)
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
elif isinstance(field, serializers.UUIDField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_UUID)
|
||||
# ------ DATE & TIME
|
||||
elif isinstance(field, serializers.DateField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_DATE)
|
||||
elif isinstance(field, serializers.DateTimeField):
|
||||
return SwaggerType(type=openapi.TYPE_STRING, format=openapi.FORMAT_DATETIME)
|
||||
# ------ OTHERS
|
||||
elif isinstance(field, serializers.FileField):
|
||||
# swagger 2.0 does not support specifics about file fields, so ImageFile gets no special treatment
|
||||
# OpenAPI 3.0 does support it, so a future implementation could handle this better
|
||||
if swagger_object_type != openapi.Parameter:
|
||||
raise SwaggerGenerationError("parameter of type file is supported only in formData Parameter")
|
||||
return SwaggerType(type=openapi.TYPE_FILE)
|
||||
elif isinstance(field, serializers.DictField) and swagger_object_type == openapi.Schema:
|
||||
child_schema = serializer_field_to_swagger(field.child, ChildSwaggerType, definitions)
|
||||
return SwaggerType(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
additional_properties=child_schema
|
||||
)
|
||||
|
||||
# TODO unhandled fields: TimeField DurationField HiddenField ModelField NullBooleanField? JSONField
|
||||
|
||||
# everything else gets string by default
|
||||
return SwaggerType(type=openapi.TYPE_STRING)
|
||||
|
||||
|
||||
def find_regex(regex_field):
|
||||
"""Given a ``Field``, look for a ``RegexValidator`` and try to extract its pattern and return it as a string.
|
||||
|
||||
:param serializers.Field regex_field: the field instance
|
||||
:return: the extracted pattern, or ``None``
|
||||
:rtype: str
|
||||
"""
|
||||
regex_validator = None
|
||||
for validator in regex_field.validators:
|
||||
if isinstance(validator, RegexValidator):
|
||||
if regex_validator is not None:
|
||||
# bail if multiple validators are found - no obvious way to choose
|
||||
return None # pragma: no cover
|
||||
regex_validator = validator
|
||||
|
||||
# regex_validator.regex should be a compiled re object...
|
||||
return getattr(getattr(regex_validator, 'regex', None), 'pattern', None)
|
||||
@@ -0,0 +1,141 @@
|
||||
import warnings
|
||||
from functools import wraps
|
||||
|
||||
from django.utils.cache import add_never_cache_headers
|
||||
from django.utils.decorators import available_attrs
|
||||
from django.views.decorators.cache import cache_page
|
||||
from django.views.decorators.vary import vary_on_headers
|
||||
from rest_framework import exceptions
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from .generators import OpenAPISchemaGenerator
|
||||
from .renderers import (
|
||||
SwaggerJSONRenderer, SwaggerYAMLRenderer, SwaggerUIRenderer, ReDocRenderer, OpenAPIRenderer,
|
||||
)
|
||||
|
||||
SPEC_RENDERERS = (SwaggerYAMLRenderer, SwaggerJSONRenderer, OpenAPIRenderer)
|
||||
UI_RENDERERS = {
|
||||
'swagger': (SwaggerUIRenderer, ReDocRenderer),
|
||||
'redoc': (ReDocRenderer, SwaggerUIRenderer),
|
||||
}
|
||||
|
||||
|
||||
def deferred_never_cache(view_func):
|
||||
"""
|
||||
Decorator that adds headers to a response so that it will
|
||||
never be cached.
|
||||
"""
|
||||
|
||||
@wraps(view_func, assigned=available_attrs(view_func))
|
||||
def _wrapped_view_func(request, *args, **kwargs):
|
||||
response = view_func(request, *args, **kwargs)
|
||||
|
||||
# It is necessary to defer the add_never_cache_headers call because
|
||||
# cache_page also defers its cache update operation; if we do not defer
|
||||
# this, cache_page will give up because it will see and obey the "never
|
||||
# cache" headers
|
||||
def callback(response):
|
||||
add_never_cache_headers(response)
|
||||
return response
|
||||
|
||||
response.add_post_render_callback(callback)
|
||||
return response
|
||||
|
||||
return _wrapped_view_func
|
||||
|
||||
|
||||
def get_schema_view(info, url=None, patterns=None, urlconf=None, public=False, validators=None,
|
||||
generator_class=OpenAPISchemaGenerator,
|
||||
authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
|
||||
permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES):
|
||||
"""
|
||||
Create a SchemaView class with default renderers and generators.
|
||||
|
||||
:param .Info info: Required. Swagger API Info object
|
||||
:param str url: API base url; if left blank will be deduced from the location the view is served at
|
||||
:param patterns: passed to SchemaGenerator
|
||||
:param urlconf: passed to SchemaGenerator
|
||||
:param bool public: if False, includes only endpoints the current user has access to
|
||||
:param 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
|
||||
_auth_classes = authentication_classes
|
||||
_perm_classes = permission_classes
|
||||
validators = validators or []
|
||||
_spec_renderers = tuple(renderer.with_validators(validators) for renderer in SPEC_RENDERERS)
|
||||
|
||||
class SchemaView(APIView):
|
||||
_ignore_model_permissions = True
|
||||
schema = None # exclude from schema
|
||||
public = _public
|
||||
generator_class = _generator_class
|
||||
authentication_classes = _auth_classes
|
||||
permission_classes = _perm_classes
|
||||
renderer_classes = _spec_renderers
|
||||
|
||||
def get(self, request, version='', format=None):
|
||||
generator = self.generator_class(info, version, url, patterns, urlconf)
|
||||
schema = generator.get_schema(request, self.public)
|
||||
if schema is None:
|
||||
raise exceptions.PermissionDenied() # pragma: no cover
|
||||
return Response(schema)
|
||||
|
||||
@classmethod
|
||||
def as_cached_view(cls, cache_timeout=0, cache_kwargs=None, **initkwargs):
|
||||
"""
|
||||
Calls .as_view() and wraps the result in a cache_page decorator.
|
||||
See https://docs.djangoproject.com/en/1.11/topics/cache/
|
||||
|
||||
: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
|
||||
:param initkwargs: kwargs for .as_view()
|
||||
:return: a view instance
|
||||
"""
|
||||
cache_kwargs = cache_kwargs or {}
|
||||
view = cls.as_view(**initkwargs)
|
||||
if cache_timeout != 0:
|
||||
if not public:
|
||||
view = vary_on_headers('Cookie', 'Authorization')(view)
|
||||
view = cache_page(cache_timeout, **cache_kwargs)(view)
|
||||
view = deferred_never_cache(view) # disable in-browser caching
|
||||
elif cache_kwargs:
|
||||
warnings.warn("cache_kwargs ignored because cache_timeout is 0 (disabled)")
|
||||
return view
|
||||
|
||||
@classmethod
|
||||
def without_ui(cls, cache_timeout=0, cache_kwargs=None):
|
||||
"""
|
||||
Instantiate this view with just JSON and YAML renderers, optionally wrapped with cache_page.
|
||||
See https://docs.djangoproject.com/en/1.11/topics/cache/.
|
||||
|
||||
: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
|
||||
"""
|
||||
return cls.as_cached_view(cache_timeout, cache_kwargs, renderer_classes=_spec_renderers)
|
||||
|
||||
@classmethod
|
||||
def with_ui(cls, renderer='swagger', cache_timeout=0, cache_kwargs=None):
|
||||
"""
|
||||
Instantiate this view with a Web UI renderer, optionally wrapped with cache_page.
|
||||
See https://docs.djangoproject.com/en/1.11/topics/cache/.
|
||||
|
||||
: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
|
||||
"""
|
||||
assert renderer in UI_RENDERERS, "supported default renderers are " + ", ".join(UI_RENDERERS)
|
||||
renderer_classes = UI_RENDERERS[renderer] + _spec_renderers
|
||||
|
||||
return cls.as_cached_view(cache_timeout, cache_kwargs, renderer_classes=renderer_classes)
|
||||
|
||||
return SchemaView
|
||||
Reference in New Issue
Block a user