Python urllib.quote() Examples

The following are 30 code examples for showing how to use urllib.quote(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module urllib , or try the search function .

Example 1
Project: Paradrop   Author: ParadropLabs   File: pdutils.py    License: Apache License 2.0 6 votes vote down vote up
def urlEncodeMe(elem, safe=' '):
    """
        Converts any values that would cause JSON parsing to fail into URL percent encoding equivalents.
        This function can be used for any valid JSON type including str, dict, list.
        Returns:
            Same element properly encoded.
    """
    # What type am I?
    if isinstance(elem, dict):
        return {urlEncodeMe(key, safe): urlEncodeMe(value, safe) for key, value in six.iteritems(elem)}
    elif isinstance(elem, list):
        return [urlEncodeMe(element, safe) for element in elem]
    elif isinstance(elem, str):
        # Leave spaces alone, they are save to travel for JSON parsing
        return urllib.quote(elem, safe)
    else:
        return elem 
Example 2
Project: gist-alfred   Author: danielecook   File: Repository.py    License: MIT License 6 votes vote down vote up
def get_contents(self, path, ref=github.GithubObject.NotSet):
        """
        :calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_
        :param path: string
        :param ref: string
        :rtype: :class:`github.ContentFile.ContentFile`
        """
        assert isinstance(path, (str, unicode)), path
        assert ref is github.GithubObject.NotSet or isinstance(ref, (str, unicode)), ref
        url_parameters = dict()
        if ref is not github.GithubObject.NotSet:
            url_parameters["ref"] = ref
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/contents/" + urllib.quote(path),
            parameters=url_parameters
        )
        if isinstance(data, list):
            return [
                github.ContentFile.ContentFile(self._requester, headers, item, completed=False)
                for item in data
            ]
        return github.ContentFile.ContentFile(self._requester, headers, data, completed=True) 
Example 3
Project: gist-alfred   Author: danielecook   File: Repository.py    License: MIT License 6 votes vote down vote up
def legacy_search_issues(self, state, keyword):
        """
        :calls: `GET /legacy/issues/search/:owner/:repository/:state/:keyword <http://developer.github.com/v3/search/legacy>`_
        :param state: "open" or "closed"
        :param keyword: string
        :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Issue.Issue`
        """
        assert state in ["open", "closed"], state
        assert isinstance(keyword, (str, unicode)), keyword
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            "/legacy/issues/search/" + self.owner.login + "/" + self.name + "/" + state + "/" + urllib.quote(keyword)
        )
        return [
            github.Issue.Issue(self._requester, headers, github.Legacy.convertIssue(element), completed=False)
            for element in data["issues"]
        ] 
Example 4
Project: misp42splunk   Author: remg427   File: net.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def validate_(self, value, context=None):
        url = self.valid_url(value)
        if not url:
            raise StopValidationError(self.messages['invalid_url'])
        if self.verify_exists:
            url_string = urlquote(urlunsplit((
                url['scheme'],
                (url['host6'] or url['host4'] or url['hostn_enc']) + ':' + (url['port'] or ''),
                url['path'],
                url['query'],
                url['frag'])
                ).encode('utf-8'), safe=VALID_CHAR_STRING)
            try:
                urlopen(url_string)
            except URLError:
                raise StopValidationError(self.messages['not_found']) 
Example 5
Project: misp42splunk   Author: remg427   File: net.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def validate_(self, value, context=None):
        url = self.valid_url(value)
        if not url:
            raise StopValidationError(self.messages['invalid_url'])
        if self.verify_exists:
            url_string = urlquote(urlunsplit((
                url['scheme'],
                (url['host6'] or url['host4'] or url['hostn_enc']) + ':' + (url['port'] or ''),
                url['path'],
                url['query'],
                url['frag'])
                ).encode('utf-8'), safe=VALID_CHAR_STRING)
            try:
                urlopen(url_string)
            except URLError:
                raise StopValidationError(self.messages['not_found']) 
Example 6
Project: py   Author: pytest-dev   File: svnwc.py    License: MIT License 6 votes vote down vote up
def url_from_path(path):
    fspath = path_to_fspath(path, False)
    from urllib import quote
    if ISWINDOWS:
        match = _reg_allow_disk.match(fspath)
        fspath = fspath.replace('\\', '/')
        if match.group(1):
            fspath = '/%s%s' % (match.group(1).replace('\\', '/'),
                                quote(fspath[len(match.group(1)):]))
        else:
            fspath = quote(fspath)
    else:
        fspath = quote(fspath)
    if path.rev != -1:
        fspath = '%s@%s' % (fspath, path.rev)
    else:
        fspath = '%s@HEAD' % (fspath,)
    return 'file://%s' % (fspath,) 
Example 7
Project: watchdog   Author: flipkart-incubator   File: HTTP.py    License: Apache License 2.0 6 votes vote down vote up
def _encode_params(self, params):
        if not params:
            return ""

        key_values = []
        for k, v in params:
            k = urllib.quote(k, safe='%')
            if v is None:
                key_values.append(k)
            else:
                if isinstance(v, tuple) or isinstance(v, list):
                    # for upload fields
                    v = v[0]
                v = urllib.quote(v, safe='%')
                key_values.append("%s=%s" % (k, v))
        return "&".join(key_values) 
Example 8
Project: watchdog   Author: flipkart-incubator   File: HTTP.py    License: Apache License 2.0 6 votes vote down vote up
def _encode_params(self, params):
        if not params:
            return ""

        key_values = []
        for k, v in params:
            k = urllib.quote(k, safe='%')
            if v is None:
                key_values.append(k)
            else:
                if isinstance(v, tuple) or isinstance(v, list):
                    # for upload fields
                    v = v[0]
                v = urllib.quote(v, safe='%')
                key_values.append("%s=%s" % (k, v))
        return "&".join(key_values) 
Example 9
Project: tandem   Author: typeintandem   File: diff_match_patch.py    License: Apache License 2.0 6 votes vote down vote up
def diff_toDelta(self, diffs):
        """Crush the diff into an encoded string which describes the operations
        required to transform text1 into text2.
        E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.
        Operations are tab-separated.  Inserted text is escaped using %xx notation.

        Args:
            diffs: Array of diff tuples.

        Returns:
            Delta text.
        """
        text = []
        for (op, data) in diffs:
            if op == self.DIFF_INSERT:
                # High ascii will raise UnicodeDecodeError.  Use Unicode instead.
                data = data.encode("utf-8")
                text.append("+" + parse.quote(data, "!~*'();/?:@&=+$,# "))
            elif op == self.DIFF_DELETE:
                text.append("-%d" % len(data))
            elif op == self.DIFF_EQUAL:
                text.append("=%d" % len(data))
        return "\t".join(text) 
Example 10
Project: tandem   Author: typeintandem   File: diff_match_patch.py    License: Apache License 2.0 6 votes vote down vote up
def diff_toDelta(self, diffs):
        """Crush the diff into an encoded string which describes the operations
        required to transform text1 into text2.
        E.g. =3\t-2\t+ing  -> Keep 3 chars, delete 2 chars, insert 'ing'.
        Operations are tab-separated.  Inserted text is escaped using %xx notation.

        Args:
            diffs: Array of diff tuples.

        Returns:
            Delta text.
        """
        text = []
        for (op, data) in diffs:
            if op == self.DIFF_INSERT:
                # High ascii will raise UnicodeDecodeError.  Use Unicode instead.
                data = data.encode("utf-8")
                text.append("+" + parse.quote(data, "!~*'();/?:@&=+$,# "))
            elif op == self.DIFF_DELETE:
                text.append("-%d" % len(data))
            elif op == self.DIFF_EQUAL:
                text.append("=%d" % len(data))
        return "\t".join(text) 
Example 11
Project: pulseaudio-dlna   Author: masmu   File: renderer.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _encode_settings(self, settings, suffix=''):
        if pulseaudio_dlna.streamserver.StreamServer.HOST:
            server_ip = pulseaudio_dlna.streamserver.StreamServer.HOST
        else:
            server_ip = pulseaudio_dlna.utils.network.get_host_by_ip(self.ip)
        if not server_ip:
            raise NoSuitableHostFoundException(self.ip)
        server_port = pulseaudio_dlna.streamserver.StreamServer.PORT
        base_url = 'http://{ip}:{port}'.format(
            ip=server_ip,
            port=server_port,
        )
        data_string = ','.join(
            ['{}="{}"'.format(k, v) for k, v in settings.iteritems()])
        stream_name = '/{base_string}/{suffix}'.format(
            base_string=urllib.quote(base64.b64encode(data_string)),
            suffix=suffix,
        )
        return urlparse.urljoin(base_url, stream_name) 
Example 12
Project: browserscope   Author: elsigh   File: login.py    License: Apache License 2.0 6 votes vote down vote up
def login_redirect(application_url, continue_url, start_response):
  """Writes a login redirection URL to a user.

  This redirects to login_url with a continue parameter to return to
  continue_url. The login_url should be on the canonical front-end server,
  regardless of the host:port the user connected to.

  Args:
    application_url: The URL of the dev appserver domain
      (e.g., 'http://localhost:8080').
    continue_url: The URL to continue to after the user logs in.
    start_response: A WSGI start_response function.

  Returns:
    An (empty) iterable over strings containing the body of the HTTP response.
  """
  if not application_url.endswith('/'):
    application_url += '/'
  redirect_url = '%s%s?%s=%s' % (application_url, LOGIN_URL_RELATIVE,
                                 CONTINUE_PARAM, urllib.quote(continue_url))
  start_response('302 Requires login',
                 [('Location', redirect_url)])
  return [] 
Example 13
Project: browserscope   Author: elsigh   File: dev_appserver_login.py    License: Apache License 2.0 6 votes vote down vote up
def LoginRedirect(login_url,
                  hostname,
                  port,
                  relative_url,
                  outfile):
  """Writes a login redirection URL to a user.

  Args:
    login_url: Relative URL which should be used for handling user logins.
    hostname: Name of the host on which the webserver is running.
    port: Port on which the webserver is running.
    relative_url: String containing the URL accessed.
    outfile: File-like object to which the response should be written.
  """
  dest_url = "http://%s:%s%s" % (hostname, port, relative_url)
  redirect_url = 'http://%s:%s%s?%s=%s' % (hostname,
                                           port,
                                           login_url,
                                           CONTINUE_PARAM,
                                           urllib.quote(dest_url))
  outfile.write('Status: 302 Requires login\r\n')
  outfile.write('Location: %s\r\n\r\n' % redirect_url) 
Example 14
Project: news-corpus-builder   Author: skillachie   File: news_corpus_generator.py    License: MIT License 5 votes vote down vote up
def _encode_query(self,query):
        # TODO Python 3 urllib.parse.quote 
        return urllib.quote(query) 
Example 15
Project: Matrix-NEB   Author: matrix-org   File: url.py    License: Apache License 2.0 5 votes vote down vote up
def cmd_encode(self, event, *args):
        """URL encode text. 'url encode <text>'"""
        # use the body directly so quotes are parsed correctly.
        return urllib.quote(event["content"]["body"][12:]) 
Example 16
Project: gist-alfred   Author: danielecook   File: PullRequest.py    License: MIT License 5 votes vote down vote up
def remove_from_labels(self, label):
        """
        :calls: `DELETE /repos/:owner/:repo/issues/:number/labels/:name <http://developer.github.com/v3/issues/labels>`_
        :param label: :class:`github.Label.Label` or string
        :rtype: None
        """
        assert isinstance(label, (github.Label.Label, str, unicode)), label
        if isinstance(label, github.Label.Label):
            label = label._identity
        else:
            label = urllib.quote(label)
        headers, data = self._requester.requestJsonAndCheck(
            "DELETE",
            self.issue_url + "/labels/" + label
        ) 
Example 17
Project: gist-alfred   Author: danielecook   File: Repository.py    License: MIT License 5 votes vote down vote up
def get_dir_contents(self, path, ref=github.GithubObject.NotSet):
        """
        :calls: `GET /repos/:owner/:repo/contents/:path <http://developer.github.com/v3/repos/contents>`_
        :param path: string
        :param ref: string
        :rtype: list of :class:`github.ContentFile.ContentFile`
        """
        assert isinstance(path, (str, unicode)), path
        assert ref is github.GithubObject.NotSet or isinstance(ref, (str, unicode)), ref
        url_parameters = dict()
        if ref is not github.GithubObject.NotSet:
            url_parameters["ref"] = ref
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/contents/" + urllib.quote(path),
            parameters=url_parameters
        )

        # Handle 302 redirect response
        if headers.get('status') == '302 Found' and headers.get('location'):
            headers, data = self._requester.requestJsonAndCheck(
                "GET",
                headers['location'],
                parameters=url_parameters
            )

        return [
            github.ContentFile.ContentFile(self._requester, headers, attributes, completed=(attributes["type"] != "file"))  # Lazy completion only makes sense for files. See discussion here: https://github.com/jacquev6/PyGithub/issues/140#issuecomment-13481130
            for attributes in data
        ] 
Example 18
Project: gist-alfred   Author: danielecook   File: Label.py    License: MIT License 5 votes vote down vote up
def _identity(self):
        return urllib.quote(self.name) 
Example 19
Project: gist-alfred   Author: danielecook   File: Issue.py    License: MIT License 5 votes vote down vote up
def remove_from_labels(self, label):
        """
        :calls: `DELETE /repos/:owner/:repo/issues/:number/labels/:name <http://developer.github.com/v3/issues/labels>`_
        :param label: :class:`github.Label.Label` or string
        :rtype: None
        """
        assert isinstance(label, (github.Label.Label, str, unicode)), label
        if isinstance(label, github.Label.Label):
            label = label._identity
        else:
            label = urllib.quote(label)
        headers, data = self._requester.requestJsonAndCheck(
            "DELETE",
            self.url + "/labels/" + label
        ) 
Example 20
Project: PyScholar   Author: dnlcrl   File: query.py    License: MIT License 5 votes vote down vote up
def get_url(self):
        if self.cluster is None:
            raise QueryArgumentError('cluster query needs cluster ID')

        urlargs = {'cluster': self.cluster,
                   'num': self.num_results or ScholarConf.MAX_PAGE_RESULTS}

        for key, val in urlargs.items():
            urlargs[key] = quote(encode(val))

        return self.SCHOLAR_CLUSTER_URL % urlargs 
Example 21
Project: PyScholar   Author: dnlcrl   File: query.py    License: MIT License 5 votes vote down vote up
def get_url(self):
        if self.words is None and self.words_some is None \
           and self.words_none is None and self.phrase is None \
           and self.author is None and self.pub is None \
           and self.timeframe[0] is None and self.timeframe[1] is None \
           and self.url is None:
            raise QueryArgumentError('search query needs more parameters')

        # If we have some-words or none-words lists, we need to
        # process them so GS understands them. For simple
        # space-separeted word lists, there's nothing to do. For lists
        # of phrases we have to ensure quotations around the phrases,
        # separating them by whitespace.
        words_some = None
        words_none = None

        if self.words_some:
            words_some = self._parenthesize_phrases(self.words_some)
        if self.words_none:
            words_none = self._parenthesize_phrases(self.words_none)

        urlargs = {'start': self.starting_number or ScholarConf.STARTING_RESULT,
                   'words': self.words or '',
                   'words_some': words_some or '',
                   'words_none': words_none or '',
                   'phrase': self.phrase or '',
                   'scope': 'title' if self.scope_title else 'any',
                   'authors': self.author or '',
                   'pub': self.pub or '',
                   'ylo': self.timeframe[0] or '',
                   'yhi': self.timeframe[1] or '',
                   'patents': '0' if self.include_patents else '1',
                   'citations': '0' if self.include_citations else '1',
                   'num': self.num_results or ScholarConf.MAX_PAGE_RESULTS}

        for key, val in urlargs.items():
            urlargs[key] = quote(encode(val))

        return self.SCHOLAR_QUERY_URL % urlargs 
Example 22
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __new__(self, val='', skip_encode=False, encode_slash=False):
        if isinstance(val, UrlEncoded):
            # Don't urllib.quote something already URL encoded.
            return val
        elif skip_encode:
            return str.__new__(self, val)
        elif encode_slash:
            return str.__new__(self, urllib.parse.quote_plus(val))
        else:
            # When subclassing str, just call str's __new__ method
            # with your class and the value you want to have in the
            # new string.
            return str.__new__(self, urllib.parse.quote(val)) 
Example 23
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __add__(self, other):
        """self + other

        If *other* is not a ``UrlEncoded``, URL encode it before
        adding it.
        """
        if isinstance(other, UrlEncoded):
            return UrlEncoded(str.__add__(self, other), skip_encode=True)
        else:
            return UrlEncoded(str.__add__(self, urllib.parse.quote(other)), skip_encode=True) 
Example 24
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __radd__(self, other):
        """other + self

        If *other* is not a ``UrlEncoded``, URL _encode it before
        adding it.
        """
        if isinstance(other, UrlEncoded):
            return UrlEncoded(str.__radd__(self, other), skip_encode=True)
        else:
            return UrlEncoded(str.__add__(urllib.parse.quote(other), self), skip_encode=True) 
Example 25
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __new__(self, val='', skip_encode=False, encode_slash=False):
        if isinstance(val, UrlEncoded):
            # Don't urllib.quote something already URL encoded.
            return val
        elif skip_encode:
            return str.__new__(self, val)
        elif encode_slash:
            return str.__new__(self, urllib.parse.quote_plus(val))
        else:
            # When subclassing str, just call str's __new__ method
            # with your class and the value you want to have in the
            # new string.
            return str.__new__(self, urllib.parse.quote(val)) 
Example 26
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __radd__(self, other):
        """other + self

        If *other* is not a ``UrlEncoded``, URL _encode it before
        adding it.
        """
        if isinstance(other, UrlEncoded):
            return UrlEncoded(str.__radd__(self, other), skip_encode=True)
        else:
            return UrlEncoded(str.__add__(urllib.parse.quote(other), self), skip_encode=True) 
Example 27
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __new__(self, val='', skip_encode=False, encode_slash=False):
        if isinstance(val, UrlEncoded):
            # Don't urllib.quote something already URL encoded.
            return val
        elif skip_encode:
            return str.__new__(self, val)
        elif encode_slash:
            return str.__new__(self, urllib.parse.quote_plus(val))
        else:
            # When subclassing str, just call str's __new__ method
            # with your class and the value you want to have in the
            # new string.
            return str.__new__(self, urllib.parse.quote(val)) 
Example 28
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __add__(self, other):
        """self + other

        If *other* is not a ``UrlEncoded``, URL encode it before
        adding it.
        """
        if isinstance(other, UrlEncoded):
            return UrlEncoded(str.__add__(self, other), skip_encode=True)
        else:
            return UrlEncoded(str.__add__(self, urllib.parse.quote(other)), skip_encode=True) 
Example 29
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __radd__(self, other):
        """other + self

        If *other* is not a ``UrlEncoded``, URL _encode it before
        adding it.
        """
        if isinstance(other, UrlEncoded):
            return UrlEncoded(str.__radd__(self, other), skip_encode=True)
        else:
            return UrlEncoded(str.__add__(urllib.parse.quote(other), self), skip_encode=True) 
Example 30
Project: misp42splunk   Author: remg427   File: binding.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __add__(self, other):
        """self + other

        If *other* is not a ``UrlEncoded``, URL encode it before
        adding it.
        """
        if isinstance(other, UrlEncoded):
            return UrlEncoded(str.__add__(self, other), skip_encode=True)
        else:
            return UrlEncoded(str.__add__(self, urllib.parse.quote(other)), skip_encode=True)