def _graceful_relative_url(base_url, url): """ Return a graceful link for a URL relative to a base URL. * If they are the same, return an empty string. * If the have the same scheme and hostname, return the path & query params. * Otherwise return the full URL. """ if url == base_url: return '' base_prefix = '%s://%s' % urlparse.urlparse(base_url or '')[0:2] url_prefix = '%s://%s' % urlparse.urlparse(url or '')[0:2] if base_prefix == url_prefix and url_prefix != '://': return url[len(url_prefix):] return url
def _get_headers(url, decoders=None, credentials=None, extra_headers=None): """ Return a dictionary of HTTP headers to use in the outgoing request. """ if decoders is None: decoders = default_decoders accept = ', '.join([decoder.media_type for decoder in decoders]) headers = { 'accept': accept } if credentials: # Include any authorization credentials relevant to this domain. url_components = urlparse.urlparse(url) host = url_components.hostname if host in credentials: headers['authorization'] = credentials[host] if extra_headers: # Include any custom headers associated with this transport. headers.update(extra_headers) return headers
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 = filter_none(definitions) self._insert_extras__()
def __init__(self, info=None, _url=None, _prefix=None, _version=None, paths=None, definitions=None, **extra): """Root Swagger object. :param .Info info: info object :param str _url: URL used for setting the API host and scheme :param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable :param str _version: version string to override Info :param .Paths paths: paths object :param dict[str,.Schema] definitions: named models """ 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) assert url.netloc and url.scheme, "if given, url must have both schema and netloc" self.host = url.netloc self.schemes = [url.scheme] self.base_path = self.get_base_path(get_script_prefix(), _prefix) self.paths = paths self.definitions = filter_none(definitions) self._insert_extras__()
def __init__(self, info=None, _url=None, _prefix=None, _version=None, consumes=None, produces=None, security_definitions=None, security=None, paths=None, definitions=None, **extra): """Root Swagger object. :param .Info info: info object :param str _url: URL used for setting the API host and scheme :param str _prefix: api path prefix to use in setting basePath; this will be appended to the wsgi SCRIPT_NAME prefix or Django's FORCE_SCRIPT_NAME if applicable :param str _version: version string to override Info :param list[dict] security_definitions: list of supported authentication mechanisms :param list[dict] security: authentication mechanisms accepted by default; can be overriden in Operation :param list[str] consumes: consumed MIME types; can be overriden in Operation :param list[str] produces: produced MIME types; can be overriden in Operation :param .Paths paths: paths object :param dict[str,.Schema] definitions: named models """ 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) assert url.netloc and url.scheme, "if given, url must have both schema and netloc" self.host = url.netloc self.schemes = [url.scheme] self.base_path = self.get_base_path(get_script_prefix(), _prefix) self.consumes = consumes self.produces = produces self.security_definitions = filter_none(security_definitions) self.security = filter_none(security) self.paths = paths self.definitions = filter_none(definitions) self._insert_extras__()
def __init__(self, info, version='', url=None, patterns=None, urlconf=None): """ :param openapi.Info info: information about the API :param str version: API version string; if omitted, `info.default_version` will be used :param str url: API scheme, host and port; if ``None`` is passed and ``DEFAULT_API_URL`` is not set, the url will be inferred from the request made against the schema view, so you should generally not need to set this parameter explicitly; if the empty string is passed, no host and scheme will be emitted If `url` is not ``None`` or the empty string, it must be a scheme-absolute uri (i.e. starting with http:// or https://), and any path component is ignored; See also: :ref:`documentation on base URL construction <custom-spec-base-url>` :param patterns: if given, only these patterns will be enumerated for inclusion in the API spec :param urlconf: if patterns is not given, use this urlconf to enumerate patterns; if not given, the default urlconf is used """ self._gen = SchemaGenerator(info.title, url, info.get('description', ''), patterns, urlconf) self.info = info self.version = version self.consumes = [] self.produces = [] if url is None and swagger_settings.DEFAULT_API_URL is not None: url = swagger_settings.DEFAULT_API_URL if url: parsed_url = urlparse.urlparse(url) if parsed_url.scheme not in ('http', 'https') or not parsed_url.netloc: raise SwaggerGenerationError("`url` must be an absolute HTTP(S) url") if parsed_url.path: logger.warning("path component of api base URL %s is ignored; use FORCE_SCRIPT_NAME instead" % url)
def __call__(self, request): if not self.credentials: return request # Include any authorization credentials relevant to this domain. url_components = urlparse.urlparse(request.url) host = url_components.hostname if host in self.credentials: request.headers['Authorization'] = self.credentials[host] return request
def generate_swagger_object(document): """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) return { 'swagger': '2.0', 'info': _get_info_object(document), 'paths': _get_paths_object(document), 'host': parsed_url.netloc, }
def domain_matches(request, domain): """ Domain string matching against an outgoing request. Patterns starting with '*' indicate a wildcard domain. """ if (domain is None) or (domain == '*'): return True host = urlparse.urlparse(request.url).hostname if domain.startswith('*'): return host.endswith(domain[1:]) return host == domain
def _yaml_include(self, loader, node): url = urlparse.urljoin(self.base_url, node.value) path = urlparse.urlparse(url).path ext = posixpath.splitext(path)[1] response = requests.get(url) if ext in [".yaml", ".yml", ".raml"]: return yaml.load(response.content, self._ordered_loader) elif ext == '.json': return jsonref.loads(response.text, base_uri=self.base_url, jsonschema=True) return response.text
def debug_request(request): def request_echo(fmt, *args): click.echo(click.style('> ', fg='blue') + (fmt % args)) headers = request.headers headers['host'] = urlparse.urlparse(request.url).hostname request_echo(click.style('%s %s HTTP/1.1', bold=True), request.method, request.path_url) for key, value in sorted(headers.items()): request_echo('%s: %s', key.title(), value) if request.body: request_echo('') for line in request.body.splitlines(): request_echo(line)
def _get_headers(url, decoders, credentials=None): """ Return a dictionary of HTTP headers to use in the outgoing request. """ accept = '%s, */*' % decoders[0].media_type headers = {'accept': accept, 'user-agent': 'coreapi'} if credentials: # Include any authorization credentials relevant to this domain. url_components = urlparse.urlparse(url) host = url_components.hostname if host in credentials: headers['authorization'] = credentials[host] return headers
def _get_filename_from_url(url, content_type=None): """ Determine an output filename based on the download URL. """ parsed = urlparse.urlparse(url) final_path_component = posixpath.basename(parsed.path.rstrip('/')) filename = _safe_filename(final_path_component) suffix = guess_extension(content_type or '') if filename: if '.' not in filename: return filename + suffix return filename elif suffix: return 'download' + suffix return None
def _get_filename_from_url(url, content_type=None): """ Determine an output filename based on the download URL. """ parsed = urlparse.urlparse(url) final_path_component = posixpath.basename(parsed.path.rstrip("/")) filename = _safe_filename(final_path_component) suffix = guess_extension(content_type or "") if filename: if "." not in filename: return filename + suffix return filename elif suffix: return "download" + suffix return None
def debug_request(request): def request_echo(fmt, *args): click.echo(click.style('> ', fg='blue') + expand_args(fmt, args)) headers = request.headers headers['host'] = urlparse.urlparse(request.url).hostname request_echo(click.style('%s %s HTTP/1.1', bold=True), request.method, request.path_url) for key, value in sorted(headers.items()): request_echo('%s: %s', key.title(), value) if request.body: body_text = request.body if isinstance(body_text, bytes): body_text = body_text.decode('utf-8') request_echo('') for line in body_text.splitlines(): request_echo(line)
def transition(url, trans=None, parameters=None): url_components = urlparse.urlparse(url) scheme = url_components.scheme.lower() netloc = url_components.netloc if not scheme: raise TransportError('URL missing scheme "%s".' % url) if not netloc: raise TransportError('URL missing hostname "%s".' % url) try: transport_class = REGISTERED_SCHEMES[scheme] except KeyError: raise TransportError('Unknown URL scheme "%s".' % scheme) transport = transport_class() return transport.transition(url, trans, parameters)
def _get_headers(url, decoders, credentials=None): """ Return a dictionary of HTTP headers to use in the outgoing request. """ accept = '%s, */*' % decoders[0].media_type headers = { 'accept': accept, 'user-agent': 'coreapi' } if credentials: # Include any authorization credentials relevant to this domain. url_components = urlparse.urlparse(url) host = url_components.hostname if host in credentials: headers['authorization'] = credentials[host] return headers
def determine_transport(transports, url): """ Given a URL determine the appropriate transport instance. """ url_components = urlparse.urlparse(url) scheme = url_components.scheme.lower() netloc = url_components.netloc if not scheme: raise exceptions.NetworkError("URL missing scheme '%s'." % url) if not netloc: raise exceptions.NetworkError("URL missing hostname '%s'." % url) for transport in transports: if scheme in transport.schemes: return transport raise exceptions.NetworkError("Unsupported URL scheme '%s'." % scheme)
def determine_transport(transports, url): """ Given a URL determine the appropriate transport instance. """ url_components = urlparse.urlparse(url) scheme = url_components.scheme.lower() netloc = url_components.netloc if not scheme: raise exceptions.TransportError("URL missing scheme '%s'." % url) if not netloc: raise exceptions.TransportError("URL missing hostname '%s'." % url) for transport in transports: if scheme in transport.schemes: return transport raise exceptions.TransportError("Unsupported URL scheme '%s'." % scheme)
def debug_request(request): def request_echo(fmt, *args): click.echo(click.style('> ', fg='blue') + expand_args(fmt, args)) request_echo(click.style('%s %s HTTP/1.1', bold=True), request.method, request.path_url) if 'host' not in request.headers: request_echo('Host: %s', urlparse.urlparse(request.url).netloc) for key, value in sorted(request.headers.items()): request_echo('%s: %s', key.title(), value) if request.body: body_text = request.body if isinstance(body_text, bytes): body_text = body_text.decode('utf-8') request_echo('') for line in body_text.splitlines(): request_echo(line)
def generate_swagger_object(document): """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) swagger = OrderedDict() swagger['swagger'] = '2.0' swagger['info'] = OrderedDict() swagger['info']['title'] = document.title swagger['info']['version'] = '' # Required by the spec if parsed_url.netloc: swagger['host'] = parsed_url.netloc if parsed_url.scheme: swagger['schemes'] = [parsed_url.scheme] swagger['paths'] = _get_paths_object(document) return swagger
def _get_headers(url, decoders, credentials=None): """ Return a dictionary of HTTP headers to use in the outgoing request. """ accept_media_types = decoders[0].get_media_types() if '*/*' not in accept_media_types: accept_media_types.append('*/*') headers = { 'accept': ', '.join(accept_media_types), 'user-agent': 'coreapi' } if credentials: # Include any authorization credentials relevant to this domain. url_components = urlparse.urlparse(url) host = url_components.hostname if host in credentials: headers['authorization'] = credentials[host] return headers
def _get_document_base_url(data, base_url=None): """ Get the base url to use when constructing absolute paths from the relative ones provided in the schema defination. """ prefered_schemes = ['https', 'http'] if base_url: url_components = urlparse.urlparse(base_url) default_host = url_components.netloc default_scheme = url_components.scheme else: default_host = '' default_scheme = None host = _get_string(data, 'host', default=default_host) path = _get_string(data, 'basePath', default='/') path = '/' + path.lstrip('/') path = path.rstrip('/') + '/' if not host: # No host is provided, and we do not have an initial URL. return path schemes = _get_list(data, 'schemes') if not schemes: # No schemes provided, use the initial URL, or a fallback. scheme = default_scheme or prefered_schemes[0] elif default_scheme in schemes: # Schemes provided, the initial URL matches one of them. scheme = default_scheme else: # Schemes provided, the initial URL does not match, pick a fallback. for scheme in prefered_schemes: if scheme in schemes: break else: raise ParseError('Unsupported transport schemes "%s"' % schemes) return '%s://%s%s' % (scheme, host, path)
def generate_swagger_object(document): """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) swagger = OrderedDict() swagger['swagger'] = '2.0' swagger['info'] = OrderedDict() swagger['info']['title'] = document.title swagger['info']['description'] = document.description swagger['info']['version'] = '' # Required by the spec if parsed_url.netloc: swagger['host'] = parsed_url.netloc if parsed_url.scheme: swagger['schemes'] = [parsed_url.scheme] swagger['paths'] = _get_paths_object(document) return swagger
def _get_headers(url, decoders=None, credentials=None): """ Return a dictionary of HTTP headers to use in the outgoing request. """ if decoders is None: decoders = default_decoders accept = ', '.join([decoder.media_type for decoder in decoders]) headers = { 'accept': accept, 'user-agent': 'coreapi' } if credentials: # Include any authorization credentials relevant to this domain. url_components = urlparse.urlparse(url) host = url_components.hostname if host in credentials: headers['authorization'] = credentials[host] return headers
def _generate_openapi_object(document: OpenApiDocument) -> OrderedDict: """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) swagger = OrderedDict() swagger['swagger'] = '2.0' swagger['info'] = OrderedDict() swagger['info']['title'] = document.title swagger['info']['description'] = document.description swagger['info']['version'] = document.version if parsed_url.netloc: swagger['host'] = parsed_url.netloc if parsed_url.scheme: swagger['schemes'] = [parsed_url.scheme] swagger['paths'] = _get_paths_object(document) return swagger