Python urllib.parse.quote_from_bytes() Examples

The following are 30 code examples of urllib.parse.quote_from_bytes(). 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 urllib.parse , or try the search function .
Example #1
Source File: test_pathlib.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_as_uri(self):
        from urllib.parse import quote_from_bytes
        P = self.cls
        with self.assertRaises(ValueError):
            P('/a/b').as_uri()
        with self.assertRaises(ValueError):
            P('c:a/b').as_uri()
        self.assertEqual(P('c:/').as_uri(), 'file:///c:/')
        self.assertEqual(P('c:/a/b.c').as_uri(), 'file:///c:/a/b.c')
        self.assertEqual(P('c:/a/b%#c').as_uri(), 'file:///c:/a/b%25%23c')
        self.assertEqual(P('c:/a/b\xe9').as_uri(), 'file:///c:/a/b%C3%A9')
        self.assertEqual(P('//some/share/').as_uri(), 'file://some/share/')
        self.assertEqual(P('//some/share/a/b.c').as_uri(),
                         'file://some/share/a/b.c')
        self.assertEqual(P('//some/share/a/b%#c\xe9').as_uri(),
                         'file://some/share/a/b%25%23c%C3%A9') 
Example #2
Source File: jsonencoder.py    From vlcp with Apache License 2.0 6 votes vote down vote up
def encode_default(obj):
    if isinstance(obj, JSONBytes):
        return {'<vlcpjsonencode/urlencoded-bytes>': quote_from_bytes(obj.data)}
    elif isinstance(obj, bytes):
        return {'<vlcpjsonencode/urlencoded-bytes>': quote_from_bytes(obj)}
    elif isinstance(obj, NamedStruct):
        # Hacked in the internal getstate implementation...
        state = obj.__getstate__()
        if state[2] is not obj:
            return {'<vlcpjsonencode/namedstruct.NamedStruct>':{'type':state[1], 'data':base64.b64encode(state[0]), 'target':state[2]}}
        else:
            return {'<vlcpjsonencode/namedstruct.NamedStruct>':{'type':state[1], 'data':base64.b64encode(state[0])}}
    else:
        if hasattr(obj, 'jsonencode'):
            try:
                key = '<vlcpjsonencode/' + type(obj).__module__ + '.' + type(obj).__name__ + '>'
            except AttributeError:
                raise TypeError(repr(obj) + " is not JSON serializable")
            else:
                return {key : obj.jsonencode()}
        else:
            raise TypeError(repr(obj) + " is not JSON serializable") 
Example #3
Source File: path.py    From vistir with ISC License 5 votes vote down vote up
def path_to_url(path):
    # type: (TPath) -> Text
    """Convert the supplied local path to a file uri.

    :param str path: A string pointing to or representing a local path
    :return: A `file://` uri for the same location
    :rtype: str

    >>> path_to_url("/home/user/code/myrepo/myfile.zip")
    'file:///home/user/code/myrepo/myfile.zip'
    """
    from .misc import to_bytes

    if not path:
        return path  # type: ignore
    normalized_path = Path(normalize_drive(os.path.abspath(path))).as_posix()
    if os.name == "nt" and normalized_path[1] == ":":
        drive, _, path = normalized_path.partition(":")
        # XXX: This enables us to handle half-surrogates that were never
        # XXX: actually part of a surrogate pair, but were just incidentally
        # XXX: passed in as a piece of a filename
        quoted_path = quote(fs_encode(path))
        return fs_decode("file:///{}:{}".format(drive, quoted_path))
    # XXX: This is also here to help deal with incidental dangling surrogates
    # XXX: on linux, by making sure they are preserved during encoding so that
    # XXX: we can urlencode the backslash correctly
    bytes_path = to_bytes(normalized_path, errors="backslashreplace")
    return fs_decode("file://{}".format(quote(bytes_path))) 
Example #4
Source File: pathlib.py    From click-configfile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) 
Example #5
Source File: pathlib.py    From click-configfile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #6
Source File: pathlib.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) 
Example #7
Source File: pathlib.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #8
Source File: __init__.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(
                path.as_posix().encode('utf-8')) 
Example #9
Source File: __init__.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #10
Source File: pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) 
Example #11
Source File: pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #12
Source File: test_pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_as_uri_non_ascii(self):
        from urllib.parse import quote_from_bytes
        P = self.cls
        try:
            os.fsencode('\xe9')
        except UnicodeEncodeError:
            self.skipTest("\\xe9 cannot be encoded to the filesystem encoding")
        self.assertEqual(P('/a/b\xe9').as_uri(),
                         'file:///a/b' + quote_from_bytes(os.fsencode('\xe9'))) 
Example #13
Source File: pathlib.py    From PySnooper with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #14
Source File: pathlib.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) 
Example #15
Source File: pathlib.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #16
Source File: pathlib.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) 
Example #17
Source File: pathlib.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #18
Source File: pathlib.py    From android_universal with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) 
Example #19
Source File: pathlib.py    From android_universal with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #20
Source File: test_pathlib.py    From android_universal with MIT License 5 votes vote down vote up
def test_as_uri_non_ascii(self):
        from urllib.parse import quote_from_bytes
        P = self.cls
        try:
            os.fsencode('\xe9')
        except UnicodeEncodeError:
            self.skipTest("\\xe9 cannot be encoded to the filesystem encoding")
        self.assertEqual(P('/a/b\xe9').as_uri(),
                         'file:///a/b' + quote_from_bytes(os.fsencode('\xe9'))) 
Example #21
Source File: pathlib.py    From PySnooper with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(
                path.as_posix().encode('utf-8')) 
Example #22
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(
                path.as_posix().encode('utf-8')) 
Example #23
Source File: pathlib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #24
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #25
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(
                path.as_posix().encode('utf-8')) 
Example #26
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #27
Source File: path.py    From pipenv with MIT License 5 votes vote down vote up
def path_to_url(path):
    # type: (TPath) -> Text
    """Convert the supplied local path to a file uri.

    :param str path: A string pointing to or representing a local path
    :return: A `file://` uri for the same location
    :rtype: str

    >>> path_to_url("/home/user/code/myrepo/myfile.zip")
    'file:///home/user/code/myrepo/myfile.zip'
    """
    from .misc import to_bytes

    if not path:
        return path  # type: ignore
    normalized_path = Path(normalize_drive(os.path.abspath(path))).as_posix()
    if os.name == "nt" and normalized_path[1] == ":":
        drive, _, path = normalized_path.partition(":")
        # XXX: This enables us to handle half-surrogates that were never
        # XXX: actually part of a surrogate pair, but were just incidentally
        # XXX: passed in as a piece of a filename
        quoted_path = quote(fs_encode(path))
        return fs_decode("file:///{}:{}".format(drive, quoted_path))
    # XXX: This is also here to help deal with incidental dangling surrogates
    # XXX: on linux, by making sure they are preserved during encoding so that
    # XXX: we can urlencode the backslash correctly
    bytes_path = to_bytes(normalized_path, errors="backslashreplace")
    return fs_decode("file://{}".format(quote(bytes_path))) 
Example #28
Source File: __init__.py    From pipenv with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # Under Windows, file URIs use the UTF-8 encoding.
        drive = path.drive
        if len(drive) == 2 and drive[1] == ':':
            # It's a path on a local drive => 'file:///c:/a/b'
            rest = path.as_posix()[2:].lstrip('/')
            return 'file:///%s/%s' % (
                drive, urlquote_from_bytes(rest.encode('utf-8')))
        else:
            # It's a path on a network drive => 'file://host/share/a/b'
            return 'file:' + urlquote_from_bytes(
                path.as_posix().encode('utf-8')) 
Example #29
Source File: __init__.py    From pipenv with MIT License 5 votes vote down vote up
def make_uri(self, path):
        # We represent the path using the local filesystem encoding,
        # for portability to other applications.
        bpath = bytes(path)
        return 'file://' + urlquote_from_bytes(bpath) 
Example #30
Source File: http.py    From vlcp with Apache License 2.0 5 votes vote down vote up
def rewrite(self, path, method = None, keepresponse = True):
        "Rewrite this request to another processor. Must be called before header sent"
        if self._sendHeaders:
            raise HttpProtocolException('Cannot modify response, headers already sent')
        if getattr(self.event, 'rewritedepth', 0) >= getattr(self.protocol, 'rewritedepthlimit', 32):
            raise HttpRewriteLoopException
        newpath = urljoin(quote_from_bytes(self.path).encode('ascii'), path)
        if newpath == self.fullpath or newpath == self.originalpath:
            raise HttpRewriteLoopException
        extraparams = {}
        if keepresponse:
            if hasattr(self, 'status'):
                extraparams['status'] = self.status
            extraparams['sent_headers'] = self.sent_headers
            extraparams['sent_cookies'] = self.sent_cookies
        r = HttpRequestEvent(self.host,
                               newpath,
                               self.method if method is None else method,
                               self.connection,
                               self.connmark,
                               self.xid,
                               self.protocol,
                               headers = self.headers,
                               headerdict = self.headerdict,
                               setcookies = self.setcookies,
                               stream = self.inputstream,
                               rewritefrom = self.fullpath,
                               originalpath = self.originalpath,
                               rewritedepth = getattr(self.event, 'rewritedepth', 0) + 1,
                               **extraparams
                               )
        await self.connection.wait_for_send(r)
        self._sendHeaders = True
        self.outputstream = None