How to use the six.moves.urllib.parse.urlencode function in six

To help you get started, we’ve selected a few six examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gtalarico / airtable-python-wrapper / tests / test_airtable_class.py View on Github external
def test_match(table, mock_response_single):
    params = urlencode({"FilterByFormula": "{Value}='abc'"})
    with Mocker() as mock:
        mock.get(
            table.url_table + "?" + params,
            status_code=200,
            json={
                "records": [
                    mock_response_single,
                    mock_response_single
                ]
            },
        )
        resp = table.match("Value", "abc")
    assert resp == mock_response_single
github galaxyproject / galaxy-lib / galaxy / util / __init__.py View on Github external
parsed_url = urlparse.urlparse(base_url)
    if scheme != 'http':
        parsed_url.scheme = scheme
    assert parsed_url.scheme in ('http', 'https', 'ftp'), 'Invalid URL scheme: %s' % scheme
    if port != 80:
        url = '%s://%s:%d/%s' % (parsed_url.scheme, parsed_url.netloc.rstrip('/'), int(port), parsed_url.path)
    else:
        url = '%s://%s/%s' % (parsed_url.scheme, parsed_url.netloc.rstrip('/'), parsed_url.path.lstrip('/'))
    if len(pathspec) > 0:
        url = '%s/%s' % (url.rstrip('/'), '/'.join(pathspec))
    if parsed_url.query:
        for query_parameter in parsed_url.query.split('&'):
            key, value = query_parameter.split('=')
            params[key] = value
    if params:
        url += '?%s' % urlparse.urlencode(params, doseq=doseq)
    return url
github kubernetes-client / python / k8sclient / rest.py View on Github external
timeout = None
        if _request_timeout:
            if isinstance(_request_timeout, (int, ) if PY3 else (int, long)):
                timeout = urllib3.Timeout(total=_request_timeout)
            elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2:
                timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1])

        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'

        try:
            # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
            if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
                if query_params:
                    url += '?' + urlencode(query_params)
                if re.search('json', headers['Content-Type'], re.IGNORECASE):
                    request_body = None
                    if body:
                        request_body = json.dumps(body)
                    r = self.pool_manager.request(method, url,
                                                  body=request_body,
                                                  preload_content=_preload_content,
                                                  timeout=timeout,
                                                  headers=headers)
                elif headers['Content-Type'] == 'application/x-www-form-urlencoded':
                    r = self.pool_manager.request(method, url,
                                                  fields=post_params,
                                                  encode_multipart=False,
                                                  preload_content=_preload_content,
                                                  timeout=timeout,
                                                  headers=headers)
github lorien / captcha_solver / captcha_solver / backend / antigate.py View on Github external
def get_check_solution_request_data(self, captcha_id):
        params = {'key': self.api_key, 'action': 'get', 'id': captcha_id}
        url = urljoin(self.service_url, 'res.php?%s' % urlencode(params))
        return {'url': url, 'post_data': None}
github beetbox / beets / beetsplug / plexupdate.py View on Github external
def append_token(url, token):
    """Appends the Plex Home token to the api call if required.
    """
    if token:
        url += '?' + urlencode({'X-Plex-Token': token})
    return url
github sagemath / sagenb / sagenb / notebook / challenge.py View on Github external
"""
        response_field = req_args.get('recaptcha_response_field', [None])[0]
        if not (response_field and len(response_field)):
            return ChallengeResponse(None, '')

        challenge_field = req_args.get('recaptcha_challenge_field', [None])[0]
        if not (challenge_field and len(challenge_field)):
            return ChallengeResponse(False, 'incorrect-captcha-sol')

        def encode_if_necessary(s):
            if isinstance(s, unicode):
                return s.encode('utf-8')
            return s

        params = urlencode({
                'privatekey': encode_if_necessary(self.private_key),
                'remoteip' :  encode_if_necessary(self.remote_ip),
                'challenge':  encode_if_necessary(challenge_field),
                'response' :  encode_if_necessary(response_field)
                })

        request = Request(
            url = "http://%s/verify" % RECAPTCHA_VERIFY_SERVER,
            data = params,
            headers = {
                "Content-type": "application/x-www-form-urlencoded",
                "User-agent": "reCAPTCHA Python"
                }
            )

        httpresp = urlopen(request)
github openstack / designate / designate / api / admin / views / base.py View on Github external
def _get_collection_href(self, request, parents=None, extra_params=None):
        params = request.GET

        if extra_params is not None:
            params.update(extra_params)

        base_href = self._get_base_href(parents)

        href = "%s?%s" % (base_href, parse.urlencode(params))

        return href.rstrip('?')
github openstack / tempest / tempest / lib / services / volume / v3 / types_client.py View on Github external
def list_volume_types(self, **params):
        """List all the volume types created.

        For a full list of available parameters, please refer to the official
        API reference:
        https://developer.openstack.org/api-ref/block-storage/v3/index.html#list-all-volume-types
        """
        url = 'types'
        if params:
            url += '?%s' % urllib.urlencode(params)

        resp, body = self.get(url)
        body = json.loads(body)
        self.expected_success(200, resp.status)
        return rest_client.ResponseBody(resp, body)
github openstack / python-glanceclient / glanceclient / v2 / tasks.py View on Github external
raise ValueError('sort_key must be one of the following: %s.'
                                 % ', '.join(SORT_KEY_VALUES))

        sort_dir = kwargs.get('sort_dir')
        if sort_dir is not None:
            if sort_dir in SORT_DIR_VALUES:
                filters['sort_dir'] = sort_dir
            else:
                raise ValueError('sort_dir must be one of the following: %s.'
                                 % ', '.join(SORT_DIR_VALUES))

        for param, value in filters.items():
            if isinstance(value, six.string_types):
                filters[param] = encodeutils.safe_encode(value)

        url = '/v2/tasks?%s' % six.moves.urllib.parse.urlencode(filters)
        for task, resp in paginate(url):
            # NOTE(flwang): remove 'self' for now until we have an elegant
            # way to pass it into the model constructor without conflict
            task.pop('self', None)
            yield self.model(**task), resp
github huaweicloud / huaweicloud-sdk-python / openstack / resource.py View on Github external
:param dict args: A dictionary of query parameters to be appended to
                          the compound URL.
        :param bool include_headers: ``True`` if header data should be
                                     included in the response body,
                                     ``False`` if not.

        :return: A ``dict`` representing the response body.
        :raises: :exc:`~openstack.exceptions.MethodNotSupported` if
                 :data:`Resource.allow_retrieve` is not set to ``True``.
        """
        if not cls.allow_retrieve:
            raise exceptions.MethodNotSupported(cls, 'retrieve')

        url = cls._get_url(path_args, resource_id)
        if args:
            url = '?'.join([url, url_parse.urlencode(args)])
        response = session.get(url, endpoint_filter=cls.service)
        body = response.json()

        if cls.resource_key:
            body = body[cls.resource_key]

        if include_headers:
            body[HEADERS] = response.headers

        return body