Python urllib.pathname2url() Examples

The following are 30 code examples for showing how to use urllib.pathname2url(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: ironpython2   Author: IronLanguages   File: test_urllib2.py    License: Apache License 2.0 6 votes vote down vote up
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace(os.sep, '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
Example 2
Project: BinderFilter   Author: dxwu   File: test_urllib2.py    License: MIT License 6 votes vote down vote up
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
Example 3
Project: Computable   Author: ktraunmueller   File: common.py    License: MIT License 6 votes vote down vote up
def file_path_to_url(path):
    """
    converts an absolute native path to a FILE URL.

    Parameters
    ----------
    path : a path in native format

    Returns
    -------
    a valid FILE URL
    """
    return urljoin('file:', pathname2url(path))


# ZipFile is not a context manager for <= 2.6
# must be tuple index here since 2.6 doesn't use namedtuple for version_info 
Example 4
Project: oss-ftp   Author: aliyun   File: test_urllib2.py    License: MIT License 6 votes vote down vote up
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
Example 5
Project: blenderseed   Author: appleseedhq   File: runtestsuite.py    License: MIT License 6 votes vote down vote up
def report_detailed_failure(self, scene, reference_filepath, output_filepath, log_filepath, error_message, num_diff, max_diff, num_comps, diff_filepath):
        self.failures += 1

        command = self.__make_update_command(output_filepath, reference_filepath)
        self.all_commands.append(command)

        self.file.write(self.__render(self.detailed_failure_template,
                                      {'project-path': scene,
                                       'ref-image-url': urllib.pathname2url(reference_filepath),
                                       'diff-image-url': urllib.pathname2url(diff_filepath) if diff_filepath is not None else "",
                                       'output-image-url': urllib.pathname2url(output_filepath),
                                       'failure-reason': error_message,
                                       'log-file-url': urllib.pathname2url(log_filepath),
                                       'log-file-path': os.path.basename(log_filepath),
                                       'max-abs-diff': max_diff,
                                       'diff-comps-count': num_diff,
                                       'diff-comps-percents': "{0:.2f}".format(100.0 * num_diff / num_comps),
                                       'update-command': command}))
        self.file.flush() 
Example 6
Project: python-percy-client   Author: percy   File: resource_loader.py    License: MIT License 6 votes vote down vote up
def build_resources(self):
        resources = []
        if not self.root_dir:
            return resources
        for root, dirs, files in os.walk(self.root_dir, followlinks=True):
            for file_name in files:
                path = os.path.join(root, file_name)
                if os.path.getsize(path) > MAX_FILESIZE_BYTES:
                    continue
                with open(path, 'rb') as f:
                    content = f.read()

                    path_for_url = pathname2url(path.replace(self.root_dir, '', 1))
                    if self.base_url[-1] == '/' and path_for_url[0] == '/':
                        path_for_url = path_for_url.replace('/', '' , 1)


                    resource_url = "{0}{1}".format(self.base_url, path_for_url)
                    resource = percy.Resource(
                        resource_url=resource_url,
                        sha=utils.sha256hash(content),
                        local_path=os.path.abspath(path),
                    )
                    resources.append(resource)
        return resources 
Example 7
Project: cloudify-dsl-parser   Author: cloudify-cosmo   File: imports.py    License: Apache License 2.0 6 votes vote down vote up
def _get_resource_location(resource_name,
                           resources_base_path,
                           current_resource_context=None):
    url_parts = resource_name.split(':')
    if url_parts[0] in ['http', 'https', 'file', 'ftp', 'plugin']:
        return resource_name

    if os.path.exists(resource_name):
        return 'file:{0}'.format(
            urllib.pathname2url(os.path.abspath(resource_name)))

    if current_resource_context:
        candidate_url = current_resource_context[
            :current_resource_context.rfind('/') + 1] + resource_name
        if utils.url_exists(candidate_url):
            return candidate_url

    if resources_base_path:
        full_path = os.path.join(resources_base_path, resource_name)
        return 'file:{0}'.format(
            urllib.pathname2url(os.path.abspath(full_path)))

    return None 
Example 8
Project: gcblue   Author: gcblue   File: test_urllib2.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
Example 9
Project: Splunking-Crime   Author: nccgroup   File: validation_util.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def validate_json(json_data, schema_file):
    with open(schema_file) as f:
        schema = json.load(f)

    schema_dir = os.path.dirname(schema_file)
    schema_path = 'file://{0}/'.format(pathname2url(schema_dir))

    resolver = RefResolver(schema_path, schema)

    try:
        Draft4Validator.check_schema(schema)
        validate(json_data, schema, resolver=resolver)
    except SchemaError as e:
        raise Exception("Failed to check JSON schema in {}: {}".format(schema_file, e.message))
    except ValidationError as e:
        raise Exception("Unable to validate data against json schema in {}: {}, {}, {}, {}, {}".format(schema_file, e.message, e.context, e.path, e.schema_path, e.cause)) 
Example 10
Project: medicare-demo   Author: ofermend   File: test_urllib2.py    License: Apache License 2.0 6 votes vote down vote up
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')
        if fname[1:2] == ":":
            fname = fname[2:]
        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'mac':
            fname = '/' + fname.replace(':', '/')
        elif os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        file_url = "file://%s" % fname
        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
Example 11
Project: CTFCrackTools-V2   Author: Acmesec   File: test_urllib2.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
Example 12
Project: guides-cms   Author: pluralsight   File: remote.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def contents_url_from_path(path):
    """
    Get github API url for contents of file from full path

    :param path: Path to file (<owner>/<repo>/<dir>/.../<filename>)
    :returns: URL suitable for a content call with github API
    """

    owner, repo, file_path = split_full_file_path(path)

    # Cannot pass unicode data to pathname2url or it can raise KeyError. Must
    # only pass URL-safe bytes. So, something like u'\u2026' will raise a
    # KeyError but if we encode it to bytes, '%E2%80%A6', things work
    # correctly.
    # http://stackoverflow.com/questions/15115588/urllib-quote-throws-keyerror
    owner = owner.encode('utf-8')
    repo = repo.encode('utf-8')
    file_path = file_path.encode('utf-8')

    return urllib.pathname2url('repos/%s/%s/contents/%s' % (owner, repo,
                                                            file_path)) 
Example 13
Project: git-aggregator   Author: acsone   File: test_repo.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def path2url(path):
    return urljoin(
        'file:', pathname2url(os.path.abspath(path))) 
Example 14
Project: ironpython2   Author: IronLanguages   File: test_urllib.py    License: Apache License 2.0 5 votes vote down vote up
def constructLocalFileUrl(self, filePath):
        return "file://%s" % urllib.pathname2url(os.path.abspath(filePath)) 
Example 15
Project: ironpython2   Author: IronLanguages   File: test_urllib.py    License: Apache License 2.0 5 votes vote down vote up
def test_basic(self):
        # Make sure simple tests pass
        expected_path = os.path.join("parts", "of", "a", "path")
        expected_url = "parts/of/a/path"
        result = urllib.pathname2url(expected_path)
        self.assertEqual(expected_url, result,
                         "pathname2url() failed; %s != %s" %
                         (result, expected_url))
        result = urllib.url2pathname(expected_url)
        self.assertEqual(expected_path, result,
                         "url2pathame() failed; %s != %s" %
                         (result, expected_path)) 
Example 16
Project: ironpython2   Author: IronLanguages   File: test_urllib.py    License: Apache License 2.0 5 votes vote down vote up
def test_quoting(self):
        # Test automatic quoting and unquoting works for pathnam2url() and
        # url2pathname() respectively
        given = os.path.join("needs", "quot=ing", "here")
        expect = "needs/%s/here" % urllib.quote("quot=ing")
        result = urllib.pathname2url(given)
        self.assertEqual(expect, result,
                         "pathname2url() failed; %s != %s" %
                         (expect, result))
        expect = given
        result = urllib.url2pathname(result)
        self.assertEqual(expect, result,
                         "url2pathname() failed; %s != %s" %
                         (expect, result))
        given = os.path.join("make sure", "using_quote")
        expect = "%s/using_quote" % urllib.quote("make sure")
        result = urllib.pathname2url(given)
        self.assertEqual(expect, result,
                         "pathname2url() failed; %s != %s" %
                         (expect, result))
        given = "make+sure/using_unquote"
        expect = os.path.join("make+sure", "using_unquote")
        result = urllib.url2pathname(given)
        self.assertEqual(expect, result,
                         "url2pathname() failed; %s != %s" %
                         (expect, result)) 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_urllib2.py    License: Apache License 2.0 5 votes vote down vote up
def sanepathname2url(path):
    import urllib
    urlpath = urllib.pathname2url(path)
    if os.name == "nt" and urlpath.startswith("///"):
        urlpath = urlpath[2:]
    # XXX don't ask me about the mac...
    return urlpath 
Example 18
Project: aumfor   Author: virtualrealitysystems   File: fileparam.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_location(_option, _opt_str, value, parser):
    """Sets the location variable in the parser to the filename in question"""
    if not os.path.exists(os.path.abspath(value)):
        debug.error("The requested file doesn't exist")
    if parser.values.location == None:
        slashes = "//"
        # Windows pathname2url decides to convert C:\blah to ///C:/blah
        # So to keep the URLs correct, we only add file: rather than file://
        if sys.platform.startswith('win'):
            slashes = ""
        parser.values.location = "file:" + slashes + urllib.pathname2url(os.path.abspath(value)) 
Example 19
Project: vnpy_crypto   Author: birforce   File: common_imports.py    License: MIT License 5 votes vote down vote up
def path2url(path):
    return urlparse.urljoin(
        'file:', pathname2url(path)) 
Example 20
Project: BinderFilter   Author: dxwu   File: test_urllib.py    License: MIT License 5 votes vote down vote up
def constructLocalFileUrl(self, filePath):
        return "file://%s" % urllib.pathname2url(os.path.abspath(filePath)) 
Example 21
Project: BinderFilter   Author: dxwu   File: test_urllib.py    License: MIT License 5 votes vote down vote up
def test_basic(self):
        # Make sure simple tests pass
        expected_path = os.path.join("parts", "of", "a", "path")
        expected_url = "parts/of/a/path"
        result = urllib.pathname2url(expected_path)
        self.assertEqual(expected_url, result,
                         "pathname2url() failed; %s != %s" %
                         (result, expected_url))
        result = urllib.url2pathname(expected_url)
        self.assertEqual(expected_path, result,
                         "url2pathame() failed; %s != %s" %
                         (result, expected_path)) 
Example 22
Project: BinderFilter   Author: dxwu   File: test_urllib.py    License: MIT License 5 votes vote down vote up
def test_quoting(self):
        # Test automatic quoting and unquoting works for pathnam2url() and
        # url2pathname() respectively
        given = os.path.join("needs", "quot=ing", "here")
        expect = "needs/%s/here" % urllib.quote("quot=ing")
        result = urllib.pathname2url(given)
        self.assertEqual(expect, result,
                         "pathname2url() failed; %s != %s" %
                         (expect, result))
        expect = given
        result = urllib.url2pathname(result)
        self.assertEqual(expect, result,
                         "url2pathname() failed; %s != %s" %
                         (expect, result))
        given = os.path.join("make sure", "using_quote")
        expect = "%s/using_quote" % urllib.quote("make sure")
        result = urllib.pathname2url(given)
        self.assertEqual(expect, result,
                         "pathname2url() failed; %s != %s" %
                         (expect, result))
        given = "make+sure/using_unquote"
        expect = os.path.join("make+sure", "using_unquote")
        result = urllib.url2pathname(given)
        self.assertEqual(expect, result,
                         "url2pathname() failed; %s != %s" %
                         (expect, result)) 
Example 23
Project: BinderFilter   Author: dxwu   File: test_urllib2.py    License: MIT License 5 votes vote down vote up
def sanepathname2url(path):
    import urllib
    urlpath = urllib.pathname2url(path)
    if os.name == "nt" and urlpath.startswith("///"):
        urlpath = urlpath[2:]
    # XXX don't ask me about the mac...
    return urlpath 
Example 24
Project: oss-ftp   Author: aliyun   File: test_urllib.py    License: MIT License 5 votes vote down vote up
def constructLocalFileUrl(self, filePath):
        return "file://%s" % urllib.pathname2url(os.path.abspath(filePath)) 
Example 25
Project: oss-ftp   Author: aliyun   File: test_urllib.py    License: MIT License 5 votes vote down vote up
def test_basic(self):
        # Make sure simple tests pass
        expected_path = os.path.join("parts", "of", "a", "path")
        expected_url = "parts/of/a/path"
        result = urllib.pathname2url(expected_path)
        self.assertEqual(expected_url, result,
                         "pathname2url() failed; %s != %s" %
                         (result, expected_url))
        result = urllib.url2pathname(expected_url)
        self.assertEqual(expected_path, result,
                         "url2pathame() failed; %s != %s" %
                         (result, expected_path)) 
Example 26
Project: oss-ftp   Author: aliyun   File: test_urllib.py    License: MIT License 5 votes vote down vote up
def test_quoting(self):
        # Test automatic quoting and unquoting works for pathnam2url() and
        # url2pathname() respectively
        given = os.path.join("needs", "quot=ing", "here")
        expect = "needs/%s/here" % urllib.quote("quot=ing")
        result = urllib.pathname2url(given)
        self.assertEqual(expect, result,
                         "pathname2url() failed; %s != %s" %
                         (expect, result))
        expect = given
        result = urllib.url2pathname(result)
        self.assertEqual(expect, result,
                         "url2pathname() failed; %s != %s" %
                         (expect, result))
        given = os.path.join("make sure", "using_quote")
        expect = "%s/using_quote" % urllib.quote("make sure")
        result = urllib.pathname2url(given)
        self.assertEqual(expect, result,
                         "pathname2url() failed; %s != %s" %
                         (expect, result))
        given = "make+sure/using_unquote"
        expect = os.path.join("make+sure", "using_unquote")
        result = urllib.url2pathname(given)
        self.assertEqual(expect, result,
                         "url2pathname() failed; %s != %s" %
                         (expect, result)) 
Example 27
Project: oss-ftp   Author: aliyun   File: test_urllib2.py    License: MIT License 5 votes vote down vote up
def sanepathname2url(path):
    import urllib
    urlpath = urllib.pathname2url(path)
    if os.name == "nt" and urlpath.startswith("///"):
        urlpath = urlpath[2:]
    # XXX don't ask me about the mac...
    return urlpath 
Example 28
Project: pyaaf2   Author: markreidvfx   File: ama.py    License: MIT License 5 votes vote down vote up
def create_network_locator(f, absolute_path):
    n = f.create.NetworkLocator()
    if sys.version_info[0] < 3:
        import urllib
        n['URLString'].value = 'file://' + urllib.pathname2url(absolute_path)
    else:
        import pathlib
        n['URLString'].value = pathlib.Path(absolute_path).as_uri()

    return n 
Example 29
Project: blenderseed   Author: appleseedhq   File: runtestsuite.py    License: MIT License 5 votes vote down vote up
def report_simple_failure(self, scene, reference_filepath, output_filepath, log_filepath, error_message):
        self.failures += 1

        command = self.__make_update_command(output_filepath, reference_filepath)
        self.all_commands.append(command)

        self.file.write(self.__render(self.simple_failure_template,
                                      {'project-path': scene,
                                       'ref-image-url': urllib.pathname2url(reference_filepath),
                                       'output-image-url': urllib.pathname2url(output_filepath),
                                       'failure-reason': error_message,
                                       'log-file-url': urllib.pathname2url(log_filepath),
                                       'log-file-path': os.path.basename(log_filepath),
                                       'update-command': command}))
        self.file.flush() 
Example 30
Project: cloudify-dsl-parser   Author: cloudify-cosmo   File: test_parser_api.py    License: Apache License 2.0 5 votes vote down vote up
def test_relative_file_uri_import(self):
        bottom_level_yaml = self.BASIC_TYPE
        self.make_file_with_name(bottom_level_yaml, 'bottom_level.yaml')

        mid_level_yaml = self.BASIC_PLUGIN + """
imports:
    -   \"bottom_level.yaml\""""
        mid_file_name = self.make_yaml_file(mid_level_yaml)

        top_level_yaml = self.BASIC_NODE_TEMPLATES_SECTION + """
imports:
    -   {0}""".format('file:///' + pathname2url(mid_file_name))
        result = self.parse(top_level_yaml)
        self._assert_blueprint(result)