Python six.moves.urllib.parse.quote_plus() Examples

The following are 21 code examples of six.moves.urllib.parse.quote_plus(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six.moves.urllib.parse , or try the search function .
Example #1
Source File: sentinel.py    From sentinelsat with GNU General Public License v3.0 6 votes vote down vote up
def check_query_length(query):
        """Determine whether a query to the OpenSearch API is too long.

        The length of a query string is limited to approximately 3938 characters but
        any special characters (that is, not alphanumeric or -_.*) will take up more space.

        Parameters
        ----------
        query : str
            The query string

        Returns
        -------
        float
            Ratio of the query length to the maximum length
        """
        # The server uses the Java's URLEncoder implementation internally, which we are replicating here
        effective_length = len(quote_plus(query, safe="-_.*").replace("~", "%7E"))

        return effective_length / 3938 
Example #2
Source File: utils.py    From jellyfin-kodi with GNU General Public License v3.0 6 votes vote down vote up
def unzip(path, dest, folder=None):

    ''' Unzip file. zipfile module seems to fail on android with badziperror.
    '''
    path = quote_plus(path)
    root = "zip://" + path + '/'

    if folder:

        xbmcvfs.mkdir(os.path.join(dest, folder))
        dest = os.path.join(dest, folder)
        root = get_zip_directory(root, folder)

    dirs, files = xbmcvfs.listdir(root)

    if dirs:
        unzip_recursive(root, dirs, dest)

    for file in files:
        unzip_file(os.path.join(root, file), os.path.join(dest, file))

    LOG.info("Unzipped %s", path) 
Example #3
Source File: client.py    From python-tackerclient with Apache License 2.0 6 votes vote down vote up
def _build_params_query(self, params=None):
        flag_params = []
        keyval_params = {}
        for key, value in params.items():
            if value is None:
                flag_params.append(key)
            else:
                keyval_params[key] = value

        flags_encoded = utils.safe_encode_list(flag_params) \
            if flag_params else ""
        keyval_encoded = utils.safe_encode_dict(keyval_params) \
            if keyval_params else ""

        query = ""
        for flag in flags_encoded:
            query = query + urlparse.quote_plus(flag) + '&'
        query = query + urlparse.urlencode(keyval_encoded, doseq=1)
        return query.strip('&') 
Example #4
Source File: json.py    From drms with MIT License 6 votes vote down vote up
def check_address(self, email):
        """
        Check if an email address is registered for export data
        requests.

        Parameters
        ----------
        email : string
            Email address to be verified.

        Returns
        -------
        result : dict
            Dictionary containing 'status' and 'msg'. Some status
            codes are:
                2: Email address is valid and registered
                4: Email address has neither been validated nor
                   registered
               -2: Not a valid email address
        """
        query = '?' + urlencode({
            'address': quote_plus(email), 'checkonly': '1'})
        req = self._json_request(self._server.url_check_address + query)
        return req.data 
Example #5
Source File: codec.py    From pwnypack with MIT License 6 votes vote down vote up
def enurlquote(v, plus=False):
    """
    Percent encode a string for use in an URL.

    Args:
        v(str): The value to percent encode.
        plus(bool): Use a plus symbol for spaces, otherwise use %20.

    Returns:
        str: The percent encoded string.

    Example:
        >>> from pwny import *
        >>> enurlquote('Foo Bar/Baz', True)
        'Foo+Bar/Baz
    """
    return quote_plus(v) if plus else quote(v) 
Example #6
Source File: strategies.py    From requirementslib with MIT License 6 votes vote down vote up
def auth_strings(draw, auth=auth_list()):
    auth_section = draw(auth)
    if auth_section and len(auth_section) == 2:
        user, password = auth_section
        if user and password:
            result = "{0}:{1}".format(
                urllib_parse.quote_plus(user.encode()),
                urllib_parse.quote_plus(password.encode()),
            )
        elif user and not password:
            result = urllib_parse.quote_plus(user.encode())
        elif password and not user:
            result = urllib_parse.quote_plus(password.encode())
        else:
            result = ""
    elif auth_section and len(auth_section) == 1:
        result = "{0}".format(urllib_parse.quote_plus(next(iter(auth_section)).encode()))
    else:
        result = ""
    return result 
Example #7
Source File: middleware.py    From allura with Apache License 2.0 6 votes vote down vote up
def get_tg_vars(context):
    import tg
    from allura.lib import helpers as h
    from six.moves.urllib.parse import quote, quote_plus
    context.setdefault('g', tg.app_globals)
    context.setdefault('c', tg.tmpl_context)
    context.setdefault('h', h)
    context.setdefault('request', tg.request)
    context.setdefault('response', tg.response)
    context.setdefault('url', tg.url)
    context.setdefault('tg', dict(
        config=tg.config,
        flash_obj=tg.flash,
        quote=quote,
        quote_plus=quote_plus,
        url=tg.url)) 
Example #8
Source File: test_oauth2.py    From box-python-sdk with Apache License 2.0 6 votes vote down vote up
def test_get_correct_authorization_url(redirect_url):
    # pylint:disable=redefined-outer-name
    fake_client_id = 'fake_client_id'
    fake_client_secret = 'fake_client_secret'
    oauth2 = OAuth2(
        client_id=fake_client_id,
        client_secret=fake_client_secret,
    )
    auth_url, csrf_token = oauth2.get_authorization_url(redirect_url=redirect_url)
    expected_auth_url_format = '{0}?state={1}&response_type=code&client_id={2}'
    if redirect_url:
        expected_auth_url_format += '&redirect_uri={3}'
    assert auth_url == expected_auth_url_format.format(
        API.OAUTH2_AUTHORIZE_URL,
        csrf_token,
        fake_client_id,
        urlparse.quote_plus((redirect_url or '').encode('utf-8')),
    )
    assert re.match('^box_csrf_token_[A-Za-z0-9]{16}$', csrf_token) 
Example #9
Source File: models.py    From logtacts with MIT License 5 votes vote down vote up
def url_quoted(self):
        return quote_plus(
            self.value.replace('\r\n', ' ').replace('\r', ' ').replace('\n', ' ')
        ) 
Example #10
Source File: autocontainerbase.py    From oio-swift with Apache License 2.0 5 votes vote down vote up
def _call_copy(self, env, start_response):
        """
        Run the retry loop (copy operations).
        """
        account, container, obj = self._convert_path(env.get('PATH_INFO'))
        if obj is None:
            # This is probably an account request
            return self.app(env, start_response)
        newpath = "/v1/%s/%s/%s" % (account, container, obj)
        env['PATH_INFO'] = newpath.encode('utf-8')

        for hdr in ("HTTP_OIO_COPY_FROM", "HTTP_X_COPY_FROM"):
            if hdr in env:
                from_value = env.get(hdr)
                from_header = hdr
                break
        else:
            raise HTTPBadRequest(body="Malformed copy-source header")

        # HTTP_X_COPY_FROM_ACCOUNT will just pass through
        if self.account_first:
            src_path = "/fake_account" + from_value
        else:
            src_path = from_value

        def modify_copy_from(orig_env, alternative):
            env_ = orig_env.copy()
            env_[from_header] = ("/%s/%s" % (
                quote_plus(alternative[1]), alternative[2])).encode('utf-8')
            return env_

        def check_container_obj(alternative):
            if not alternative[1] or not alternative[2]:
                raise HTTPBadRequest(body="Malformed copy-source header")
            return True

        return self._retry_loop(
            env, start_response, src_path,
            env_modifier=modify_copy_from,
            alt_checker=check_container_obj) 
Example #11
Source File: autocontainerbase.py    From oio-swift with Apache License 2.0 5 votes vote down vote up
def _alternatives(self, account, container, obj):
        # put S3 parts in dedicated container
        suffix = ("+segments" if container and container.endswith('+segments')
                  else "")
        if obj is None:
            yield account, container, obj
        elif self.stop_at_first_match:
            # TODO(FVE): when supported, also pass account to con_builder()
            yield account, quote_plus(self.con_builder(obj)) + suffix, obj
        else:
            for alt_container in self.con_builder.alternatives(obj):
                yield account, quote_plus(alt_container) + suffix, obj
        raise StopIteration 
Example #12
Source File: autocontainerbase.py    From oio-swift with Apache License 2.0 5 votes vote down vote up
def _convert_path(self, path):
        account, container, obj = self._extract_path(path)
        if obj is not None:
            # TODO(FVE): when supported, also pass account to con_builder()
            container = quote_plus(self.con_builder(obj))
        return account, container, obj 
Example #13
Source File: utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def build_url(scheme, host, path='/', username=None, password=None, query_params=None):
    # type: (str, str, str, str, str, dict) -> str
    """Build an URL from individual parts. Make sure that parts are properly URL-encoded."""
    if username and password:
        netloc = '{}:{}@{}'.format(quote_plus(username), quote_plus(password), host)
    else:
        netloc = host

    path_params = ""
    query = urlencode(query_params or {})
    fragment = ""

    return urlunparse([scheme, netloc, path, path_params, query, fragment]) 
Example #14
Source File: ws_client.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def websocket_call(configuration, url, query_params, _request_timeout,
                   _preload_content, headers):
    """An internal function to be called in api-client when a websocket
    connection is required."""

    # Extract the command from the list of tuples
    commands = None
    for key, value in query_params:
        if key == 'command':
            commands = value
            break

    # drop command from query_params as we will be processing it separately
    query_params = [(key, value) for key, value in query_params if
                    key != 'command']

    # if we still have query params then encode them
    if query_params:
        url += '?' + urlencode(query_params)

    # tack on the actual command to execute at the end
    if isinstance(commands, list):
        for command in commands:
            url += "&command=%s&" % quote_plus(command)
    elif commands is not None:
        url += '&command=' + quote_plus(commands)

    try:
        client = WSClient(configuration, get_websocket_url(url), headers)
        if not _preload_content:
            return client
        client.run_forever(timeout=_request_timeout)
        return WSResponse('%s' % ''.join(client.read_all()))
    except (Exception, KeyboardInterrupt, SystemExit) as e:
        raise ApiException(status=0, reason=str(e)) 
Example #15
Source File: data.py    From acousticbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def _get_youtube_query(metadata):
    """Generates a query string to search youtube for this song

    See https://developers.google.com/youtube/player_parameters#Manual_IFrame_Embeds
    for more info.
    """
    if not ('artist' in metadata and 'title' in metadata):
        return None
    else:
        return "{artist}+{title}".format(
            artist=quote_plus(metadata['artist'].encode("UTF-8")),
            title=quote_plus(metadata['title'].encode("UTF-8")),
        ) 
Example #16
Source File: test_client.py    From python-saml with MIT License 5 votes vote down vote up
def test_relay_state():
    target = build_authentication_request_simple()
    state = 'http://localhost:8080/'
    uri, _ = client.send('http://localhost', target.serialize(), state)

    relay_state_part = 'RelayState=%s' % quote_plus(state)
    assert relay_state_part in uri 
Example #17
Source File: sdo.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _to_bing_maps_url(self, params):
        url_base = "https://bing.com/maps/default.aspx?where1="
        url_ending = params[0]
        for i in range(1, len(params)):
            url_ending = url_ending + "," + params[i]

        final_url = url_base + quote_plus(url_ending) + "&lvl=16"   # level 16 zoom so long/lat searches shown more clearly
        return final_url 
Example #18
Source File: sdo.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _to_google_maps_url(self, params):
        url_base = "https://www.google.com/maps/search/?api=1&query="
        url_ending = params[0]
        for i in range(1, len(params)):
            url_ending = url_ending + "," + params[i]

        final_url = url_base + quote_plus(url_ending)
        return final_url 
Example #19
Source File: request.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def add_filter(self, expr):
        expr = quote_plus(expr)
        self._filters.append(expr) 
Example #20
Source File: utils.py    From sagemaker-python-sdk with Apache License 2.0 4 votes vote down vote up
def generate_tensorboard_url(domain, bucket_paths):
    """Generate Tensorboard URL for given list of s3 buckets

    Args:
        domain: JupyterLab app domain
        bucket_paths: List of S3 bucket paths in format `bucket/path`
                      or a single string in the same format

    Returns:
        str: Tensorboard URL

    Raises:
        AttributeError if invalid inputs are passed
    """

    def trim_prefix(s, prefix):
        if s.startswith(prefix):
            return s[len(prefix) :]
        return s

    def encode_s3_url(s3_url):
        if not s3_url:
            raise AttributeError("bucket_paths element should not be empty")
        s3_url = trim_prefix(s3_url, S3_PREFIX)
        return parse.quote_plus("{}{}".format(S3_PREFIX, s3_url))

    if not isinstance(domain, six.string_types):
        raise AttributeError("domain parameter should be string")

    if len(domain) == 0:
        raise AttributeError("domain parameter should not be empty")

    if isinstance(bucket_paths, six.string_types):
        bucket_paths = [bucket_paths]
    elif not isinstance(bucket_paths, list):
        raise AttributeError("bucket paths should be a list or a string")

    if len(bucket_paths) == 0:
        raise AttributeError("bucket_paths parameter should not be empty list")

    domain = trim_prefix(domain, HTTPS_PREFIX)
    domain = trim_prefix(domain, HTTP_PREFIX)

    s3_urls = map(encode_s3_url, bucket_paths)
    query = ",".join(s3_urls)

    return "https://{}/tensorboard/default?s3urls={}".format(domain, query) 
Example #21
Source File: utils.py    From kubeshift with GNU Lesser General Public License v3.0 4 votes vote down vote up
def selectors_to_qs(selectors):
    """Convert list of selector dict to query string.

    :param list selectors: list of dicts representing selectors
    :returns: querystring
    :rtype: str|None
    """
    qs = None
    if not isinstance(selectors, list) or not selectors:
        return qs

    qs_list = []
    for s in selectors:
        key = s.get('key')
        if not key:
            # invalid w/o key
            break
        val = s.get('value')
        # default missing op to equal with the assumption that the
        # intent is exists or equal.
        op = s.get('op', '=')

        # set-based has equivalence to equality-based, therefore leverage
        # the set-based formatting
        if op in ['=', '==', 'in']:
            # in / equality / exists
            if val is None:
                qs_list.append('{}'.format(key))
            else:
                if not isinstance(val, list):
                    val = [val]
                qs_list.append('{} in ({})'.format(key, ','.join(val)))

        elif op in ['!=', 'notin']:
            # not in / non-equality / not exists
            if val is None:
                qs_list.append('!{}'.format(key))
            else:
                if not isinstance(val, list):
                    val = [val]
                qs_list.append('{} notin ({})'.format(key, ','.join(val)))
        else:
            # unknown op
            break
    else:
        # successfully processed each selector; format as proper query string
        qs = '?labelSelector=' + url_parse.quote_plus(','.join(qs_list))

    return qs