def get(self, request): apis = [] resources = self.get_resources() for path in resources: apis.append({ 'path': "/%s" % path, }) return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': "%s/api-docs" % get_full_base_path(request, strip_pathname=False), 'apis': apis, 'info': SWAGGER_SETTINGS.get( 'info', { 'contact': '', 'description': '', 'license': '', 'licenseUrl': '', 'termsOfServiceUrl': '', 'title': '', }), })
def get_permission_class(self, request): if SWAGGER_SETTINGS.get('is_superuser') and not request.user.is_superuser: return IsAdminUser if SWAGGER_SETTINGS.get('is_authenticated') and not request.user.is_authenticated(): return IsAuthenticated return AllowAny
def get(self, request, *args, **kwargs): if not self.has_permission(request): return self.handle_permission_denied(request) template_name = SWAGGER_SETTINGS.get('template_path') data = { 'swagger_settings': { 'discovery_url': "%s/api-docs" % get_full_base_path(request, strip_pathname=False), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'token_type': SWAGGER_SETTINGS.get('token_type'), 'enabled_methods': mark_safe(json.dumps(SWAGGER_SETTINGS.get('enabled_methods'))), 'doc_expansion': SWAGGER_SETTINGS.get('doc_expansion', ''), } } response = render_to_response(template_name, RequestContext(request, data)) return response
def get_full_base_path(request): protocol = SWAGGER_SETTINGS.get('protocol', 'http') if 'base_path' in SWAGGER_SETTINGS: return ("%s://%s" % (protocol, SWAGGER_SETTINGS.get( 'base_path', '').rstrip('/'))).rstrip('/') else: return ('%s://%s%s' % (protocol, request.get_host(), request.path)).rstrip('/')
def has_permission(self, request): if SWAGGER_SETTINGS.get('is_superuser') and not request.user.is_superuser: return False if SWAGGER_SETTINGS.get('is_authenticated') and not request.user.is_authenticated(): return False return True
def get_resources(self): api_prefixes = SWAGGER_SETTINGS.get('api_prefixes') if api_prefixes: return [endpoint.strip("/") for endpoint in api_prefixes] urlparser = UrlParser() apis = urlparser.get_apis(exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces')) return urlparser.get_top_level_apis(apis)
def get_base_path(self): protocol = SWAGGER_SETTINGS.get('protocol', 'http') if 'base_path' in SWAGGER_SETTINGS: return ( "%s://%s/api-docs" % (protocol, SWAGGER_SETTINGS.get('base_path', '').rstrip('/'))) else: return ('%s://%s%s' % (protocol, self.request.get_host(), self.request.path)).rstrip('/')
def get(self, request, *args, **kwargs): template_name = "rest_framework_swagger/index.html" data = { 'settings': { 'discovery_url': "%sapi-docs/" % request.build_absolute_uri(), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'enabled_methods': mark_safe(SWAGGER_SETTINGS.get('enabled_methods')) } } response = render_to_response(template_name, RequestContext(request, data)) return response
def get_api_declaration(self, path, urlconf): api_full_uri = SWAGGER_SETTINGS.get('api_full_uri') apis = self.get_api_for_resource(path, urlconf=urlconf) generator = DocumentationGenerator() return { 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': api_full_uri.rstrip('/'), 'resourcePath': '/' + path, 'apis': generator.generate(apis), 'models': generator.get_models(apis), }
def get_api_declaration(self, path): api_full_uri = SWAGGER_SETTINGS.get('api_full_uri') apis = self.get_api_for_resource(path) generator = DocumentationGenerator() return { 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': api_full_uri.rstrip('/'), 'resourcePath': '/' + path, 'apis': generator.generate(apis), 'models': generator.get_models(apis), }
def get(self, request, api_version=None, *args, **kwargs): if api_version not in SWAGGER_SETTINGS.get('available_api_versions') and SWAGGER_SETTINGS['api_version']: return redirect(reverse('django.swagger.base.view', args=(SWAGGER_SETTINGS['api_version'],))) SWAGGER_SETTINGS['api_version'] = api_version if not self.has_permission(request): return self.handle_permission_denied(request) template_name = SWAGGER_SETTINGS.get('template_path') data = { 'swagger_settings': { 'discovery_url': "%sapi-docs/" % request.build_absolute_uri(), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'token_type': SWAGGER_SETTINGS.get('token_type'), 'enabled_methods': mark_safe( json.dumps(SWAGGER_SETTINGS.get('enabled_methods'))), 'doc_expansion': SWAGGER_SETTINGS.get('doc_expansion', ''), 'api_version': api_version, 'available_api_versions': SWAGGER_SETTINGS.get('available_api_versions', []), 'default_api_version': SWAGGER_SETTINGS.get('default_api_version'), } } response = render_to_response(template_name, RequestContext(request, data)) return response
def get_full_base_path(request, strip_pathname=True): protocol = SWAGGER_SETTINGS.get('protocol', 'http') if 'base_path' in SWAGGER_SETTINGS: return re.sub( r'/*$', '', ('{uri.scheme}://{uri.hostname}/' if strip_pathname else '{uri.scheme}://{uri.hostname}/{uri.path}').format(uri=urlparse( "%s://%s/" % (protocol, SWAGGER_SETTINGS.get('base_path', '').rstrip('/')))) + SWAGGER_SETTINGS.get("api_path")) else: return ('%s://%s%s' % (protocol, request.get_host(), request.path)).rstrip('/')
def get_resources(self): urlparser = UrlParser() apis = urlparser.get_apis( exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces')) resources = urlparser.get_top_level_apis(apis) return resources
def get_resource_listing(self): apis = self.get_apis() data = { 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'apis': apis, 'info': SWAGGER_SETTINGS.get('info', { 'contact': '', 'description': '', 'license': '', 'licenseUrl': '', 'termsOfServiceUrl': '', 'title': '', }), } return data
def get_renderer_classes(self, request): render_class_list = [] class_tuple = SWAGGER_SETTINGS.get('renderer_classes', None) if not class_tuple: render_class_list.append(JSONRenderer) for render_class in class_tuple: try: dot = render_class.rindex('.') except ValueError: raise exceptions.ImproperlyConfigured, '{0:s} isn\'t a ' \ 'renderer module' \ .format(render_class) render_module, render_classname = render_class[:dot], render_class[ (dot + 1):] try: mod = __import__(render_module, {}, {}, ['']) except ImportError, e: raise exceptions.ImproperlyConfigured, 'Error importing ' \ 'renderer module {' \ '0:s}: "{' \ '1:s}"'.format( render_module, e) try: render_class_list.append(getattr(mod, render_classname)) except AttributeError: raise exceptions.ImproperlyConfigured, 'Renderer module ' \ '"{0:s}" does not ' \ 'define ' \ 'a "{0:s}" class' \ .format(render_module, render_classname)
def get_resource_listing(self, urlconf): apis = self.get_apis(urlconf=urlconf) data = { 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'apis': apis, 'info': SWAGGER_SETTINGS.get('info', { # 'contact': '', 'description': '', 'license': '', 'licenseUrl': '', 'termsOfServiceUrl': '', 'title': '', }), } return data
def get(self, request, *args, **kwargs): if not self.has_permission(request): raise PermissionDenied() template_name = "rest_framework_swagger/index.html" data = { 'settings': { 'discovery_url': "%sapi-docs/" % request.build_absolute_uri(), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'enabled_methods': mark_safe(SWAGGER_SETTINGS.get('enabled_methods')) } } response = render_to_response(template_name, RequestContext(request, data)) return response
def handle_resource_access(self, request, resource): resource_access_handler = self.resource_access_handler or SWAGGER_SETTINGS.get('resource_access_handler') if isinstance(resource_access_handler, six.string_types): resource_access_handler = import_string(resource_access_handler) if resource_access_handler: return resource_access_handler(request, resource) return True
def handle_resource_access(self, request, resource): resource_access_handler = SWAGGER_SETTINGS.get('resource_access_handler') if isinstance(resource_access_handler, six.string_types): resource_access_handler = import_string(resource_access_handler) if resource_access_handler: return resource_access_handler(request, resource) return True
def initial(self, request, *args, **kwargs): self.permission_classes = (self.get_permission_class(request),) protocol = SWAGGER_SETTINGS.get('protocol', '') or ("https" if request.is_secure() else "http") self.host = request.build_absolute_uri() self.api_path = SWAGGER_SETTINGS['api_path'] self.api_full_uri = "%s://%s%s" % (protocol, request.get_host(), self.api_path) return super(APIDocView, self).initial(request, *args, **kwargs)
def get_resources(self): urlparser = UrlParser() urlconf = getattr(self.request, "urlconf", None) apis = urlparser.get_apis( urlconf=urlconf, exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces')) resources = urlparser.get_top_level_apis(apis) return resources
def get(self, request, *args, **kwargs): if not self.has_permission(request): return self.handle_permission_denied(request) template_name = "rest_framework_swagger/index.html" data = { 'swagger_settings': { 'discovery_url': "%sapi-docs/" % request.build_absolute_uri(), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'enabled_methods': mark_safe( json.dumps(SWAGGER_SETTINGS.get('enabled_methods'))) } } response = render_to_response(template_name, RequestContext(request, data)) return response
def handle_permission_denied(self, request): permission_denied_handler = SWAGGER_SETTINGS.get('permission_denied_handler') if isinstance(permission_denied_handler, six.string_types): permission_denied_handler = import_string(permission_denied_handler) if permission_denied_handler: return permission_denied_handler(request) else: raise PermissionDenied()
def get(self, request, *args, **kwargs): if not self.has_permission(request): return self.handle_permission_denied(request) template_name = SWAGGER_SETTINGS.get('template_path') data = { 'swagger_settings': { 'discovery_url': "%sapi-docs/" % request.build_absolute_uri(), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'token_type': SWAGGER_SETTINGS.get('token_type'), 'enabled_methods': mark_safe( json.dumps(SWAGGER_SETTINGS.get('enabled_methods'))) } } response = render_to_response(template_name, RequestContext(request, data)) return response
def get(self, request, *args, **kwargs): if not self.has_permission(request): return self.handle_permission_denied(request) template_name = SWAGGER_SETTINGS.get('template_path') data = { 'swagger_settings': { 'discovery_url': "%s/api-docs/" % get_full_base_path(request), 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'token_type': SWAGGER_SETTINGS.get('token_type'), 'enabled_methods': mark_safe( json.dumps(SWAGGER_SETTINGS.get('enabled_methods'))), 'doc_expansion': SWAGGER_SETTINGS.get('doc_expansion', ''), } } response = render_to_response(template_name, RequestContext(request, data)) return response
def get(self, request, *args, **kwargs): if not self.has_permission(request): raise PermissionDenied() template_name = "rest_framework_swagger/index.html" discovery_url = "{}{}docs/api-docs/".format( self.base_uri, SWAGGER_SETTINGS.get('api_path', '/')) data = { 'swagger_settings': { 'discovery_url': discovery_url, 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'enabled_methods': mark_safe( json.dumps( SWAGGER_SETTINGS.get('enabled_methods'))) }, 'release_info': self.get_git_info(), } response = render_to_response(template_name, RequestContext(request, data)) return response
def __init__(self, for_user=None): # unauthenticated user is expected to be in the form 'module.submodule.Class' if a value is present unauthenticated_user = SWAGGER_SETTINGS.get('unauthenticated_user') # attempt to load unathenticated_user class from settings if a user is not supplied if not for_user and unauthenticated_user: module_name, class_name = unauthenticated_user.rsplit(".", 1) unauthenticated_user_class = getattr(importlib.import_module(module_name), class_name) for_user = unauthenticated_user_class() self.user = for_user
def get(self, request, path): apis = self.get_api_for_resource(path) generator = DocumentationGenerator() return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', "resourcePath": "/{}".format(path), 'apis': generator.generate(apis), 'models': generator.get_models(apis), 'basePath': self.api_full_uri.rstrip('/'), })
def get(self, request, path): apis = self.get_api_for_resource(path) generator = DocumentationGenerator() return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': self.api_full_uri.rstrip('/'), 'resourcePath': '/' + path, 'apis': generator.generate(apis), 'models': generator.get_models(apis), })
def get(self, request, *args, **kwargs): if not self.has_permission(request): raise PermissionDenied() template_name = SWAGGER_SETTINGS.get('template_path', 'rest_framework_swagger/index.html') discovery_url = (SWAGGER_SETTINGS.get('discovery_url') or "%sapi-docs/" % request.build_absolute_uri()) data = { 'swagger_settings': { 'discovery_url': discovery_url, 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'auth_scheme': SWAGGER_SETTINGS.get('auth_scheme', 'Token'), 'enabled_methods': mark_safe( json.dumps( SWAGGER_SETTINGS.get('enabled_methods'))) } } response = render_to_response(template_name, RequestContext(request, data)) return response
def get(self, request): apis = [] resources = self.get_resources() for path in resources: apis.append({ 'path': "/%s" % path, }) return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': self.host.rstrip('/'), 'apis': apis, 'info': SWAGGER_SETTINGS.get('info', { 'contact': '', 'description': '', 'license': '', 'licenseUrl': '', 'termsOfServiceUrl': '', 'title': '', }), })
def get(self, request, *args, **kwargs): if not self.has_permission(request): raise PermissionDenied() template_name = "rest_framework_swagger/index.html" discovery_url = "{}{}docs/api-docs/".format( self.base_uri, SWAGGER_SETTINGS.get('api_path', '/')) data = { 'swagger_settings': { 'discovery_url': discovery_url, 'api_key': SWAGGER_SETTINGS.get('api_key', ''), 'enabled_methods': mark_safe(json.dumps(SWAGGER_SETTINGS.get('enabled_methods'))) }, 'release_info': self.get_git_info(), } response = render_to_response(template_name, RequestContext(request, data)) return response
def get(self, request): apis = [] resources = self.get_resources() normalize = lambda s: s if s.startswith('/') else "/%s" % s for path in resources: apis.append({ 'path': normalize(path), }) return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2.4', 'basePath': self.host[:-1], 'apis': apis })
def get(self, request): apis = [] resources = self.get_resources() for path in resources: apis.append({ 'path': "/%s" % path, }) return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': self.host.rstrip('/'), 'apis': apis })
def get(self, request): apis = [] resources = self.get_resources() for path in resources: apis.append({ 'path': "%s" % path, }) return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2', 'basePath': "{}{}".format(self.base_uri, request.path), 'apis': apis })
def __filter_top_level_apis__(self, root_paths): """ Returns top level APIs """ filtered_paths = set() base_path = self.__get_base_path__(root_paths) api_groups = SWAGGER_SETTINGS.get("api_groups") if api_groups is not None: return [group["path"] for group in api_groups] for path in root_paths: resource = path.replace(base_path, "").split("/")[0] filtered_paths.add(base_path + resource) return list(filtered_paths)
def get_resources(self): urlparser = UrlParser() apis = urlparser.get_apis(exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces')) # Swagger urlparser has bug that causes exclude_namespaces to not work in some cases # In our case we dont want to include all urls from all modules to same documentation # so instead we check that the apis url (current url) can be found from the endpoints url. # If not then it belogn to another module and we dont include it to documentation. filtered_apis = [] p = self.request_path.replace('api-docs/', '') for endpoint in apis: try: str(endpoint['path']).index(p) filtered_apis.append(endpoint) except ValueError: pass return urlparser.get_top_level_apis(filtered_apis)
def get(self, request): apis = [] parsed = urlparse.urlparse(self.host) host_with_path = '%s://%s%s' % (parsed.scheme, parsed.netloc, parsed.path) self.request_path = parsed.path resources = self.get_resources() for path in resources: apis.append({ 'path': "/%s" % path, }) parsed = urlparse.urlparse(self.host) return Response({ 'apiVersion': SWAGGER_SETTINGS.get('api_version', ''), 'swaggerVersion': '1.2.4', 'basePath': host_with_path, 'apis': apis })
def __init__(self, for_user=None): # unauthenticated user is expected to be in the form 'module.submodule.Class' if a value is present unauthenticated_user = SWAGGER_SETTINGS.get('unauthenticated_user') # attempt to load unathenticated_user class from settings if a user is not supplied if not for_user and unauthenticated_user: module_name, class_name = unauthenticated_user.rsplit(".", 1) unauthenticated_user_class = getattr(importlib.import_module(module_name), class_name) for_user = unauthenticated_user_class() self.user = for_user # Serializers defined in docstrings self.explicit_serializers = set() # Serializers defined in fields self.fields_serializers = set() # Response classes defined in docstrings self.explicit_response_types = dict()
def __init__(self, for_user=None): # unauthenticated user is expected to be in the form 'module.submodule.Class' if a value is present unauthenticated_user = SWAGGER_SETTINGS.get('unauthenticated_user') # attempt to load unathenticated_user class from settings if a user is not supplied if not for_user and unauthenticated_user: module_name, class_name = unauthenticated_user.rsplit(".", 1) unauthenticated_user_class = getattr( importlib.import_module(module_name), class_name) for_user = unauthenticated_user_class() self.user = for_user # Serializers defined in docstrings self.explicit_serializers = set() # Serializers defined in fields self.fields_serializers = set() # Response classes defined in docstrings self.explicit_response_types = dict()
def __init__(self, for_user=None, config=None, request=None): self.config = config # unauthenticated user is expected to be in the form 'module.submodule.Class' if a value is present unauthenticated_user = SWAGGER_SETTINGS.get("unauthenticated_user") # attempt to load unathenticated_user class from settings if a user is not supplied if not for_user and unauthenticated_user: module_name, class_name = unauthenticated_user.rsplit(".", 1) unauthenticated_user_class = getattr(importlib.import_module(module_name), class_name) for_user = unauthenticated_user_class() self.user = for_user self.request = request self._tag_matchers = list(map(import_string, self.config.get("tag_matchers"))) self._operation_filters = list(map(import_string, self.config.get("operation_filters", []))) # Serializers defined in docstrings self.body_serializers = set() # Serializers defined in fields self.fields_serializers = set() # Response classes defined in docstrings self.explicit_response_types = dict()
def get_full_base_path(request): protocol = SWAGGER_SETTINGS.get('protocol', 'http') if 'base_path' in SWAGGER_SETTINGS: return ("%s://%s" % (protocol, SWAGGER_SETTINGS.get('base_path', '').rstrip('/'))).rstrip('/') else: return ('%s://%s%s' % (protocol, request.get_host(), request.path)).rstrip('/')
def get_api_for_resource(self, filter_path): urlparser = UrlParser() return urlparser.get_apis( filter_path=filter_path, exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces'))
def get_api_for_resource(self, filter_path): urlparser = UrlParser() return urlparser.get_apis(filter_path=filter_path, exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces'))
def get_resources(self): urlparser = UrlParser() apis = urlparser.get_apis(exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces')) resources = urlparser.get_top_level_apis(apis) return resources
def get_resources(self): urlparser = UrlParser() urlconf = getattr(self.request, "urlconf", None) apis = urlparser.get_apis(urlconf=urlconf, exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces')) resources = urlparser.get_top_level_apis(apis) return resources