urllib.request.url2pathname

Here are the examples of the python api urllib.request.url2pathname taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

10 Examples 7

Example 1

Project: TrustRouter Source File: test_urllib.py
Function: test_ntpath
    @unittest.skipUnless(sys.platform == 'win32',
                         'test specific to the urllib.url2path function.')
    def test_ntpath(self):
        given = ('/C:/', '///C:/', '/C|//')
        expect = 'C:\\'
        for url in given:
            result = urllib.request.url2pathname(url)
            self.assertEqual(expect, result,
                             'urllib.request..url2pathname() failed; %s != %s' %
                             (expect, result))
        given = '///C|/path'
        expect = 'C:\\path'
        result = urllib.request.url2pathname(given)
        self.assertEqual(expect, result,
                         'urllib.request.url2pathname() failed; %s != %s' %
                         (expect, result))

Example 2

Project: gumpy Source File: __init__.py
    def __call__(self, environ, start_response):
        filepath = os.path.dirname(__file__) + url2pathname(environ['SCRIPT_NAME'] + environ['PATH_INFO'])
        bn, ext = os.path.splitext(filepath)
        try:
            with open(filepath, 'rb') as fd:
                if ext in mimetypes.types_map:
                    start_response(HTTP_STATUS(200), [('Content-Type', mimetypes.types_map[ext]), ])
                else:
                    start_response(HTTP_STATUS(200), [('Content-Type', 'application/octet-stream'), ])
                return [fd.read(), ]
        except (OSError, IOError):
            start_response(HTTP_STATUS(404), [('Content-Type', 'text/plain'), ])
            return ['File not found'.encode('utf-8')]

Example 3

Project: Live-Blog Source File: images.py
    def run(self):
        figwidth = self.options.pop('figwidth', None)
        figclasses = self.options.pop('figclass', None)
        align = self.options.pop('align', None)
        (image_node,) = Image.run(self)
        if isinstance(image_node, nodes.system_message):
            return [image_node]
        figure_node = nodes.figure('', image_node)
        if figwidth == 'image':
            if PIL and self.state.docuement.settings.file_insertion_enabled:
                imagepath = urllib.request.url2pathname(image_node['uri'])
                try:
                    img = PIL.Image.open(
                            imagepath.encode(sys.getfilesystemencoding()))
                except (IOError, UnicodeEncodeError):
                    pass # TODO: warn?
                else:
                    self.state.docuement.settings.record_dependencies.add(
                        imagepath.replace('\\', '/'))
                    figure_node['width'] = img.size[0]
                    del img
        elif figwidth is not None:
            figure_node['width'] = figwidth
        if figclasses:
            figure_node['classes'] += figclasses
        if align:
            figure_node['align'] = align
        if self.content:
            node = nodes.Element()          # anonymous container for parsing
            self.state.nested_parse(self.content, self.content_offset, node)
            first_node = node[0]
            if isinstance(first_node, nodes.paragraph):
                caption = nodes.caption(first_node.rawsource, '',
                                        *first_node.children)
                figure_node += caption
            elif not (isinstance(first_node, nodes.comment)
                      and len(first_node) == 0):
                error = self.state_machine.reporter.error(
                      'Figure caption must be a paragraph or empty comment.',
                      nodes.literal_block(self.block_text, self.block_text),
                      line=self.lineno)
                return [figure_node, error]
            if len(node) > 1:
                figure_node += nodes.legend('', *node[1:])
        return [figure_node]

Example 4

Project: OmniMarkupPreviewer Source File: images.py
    def run(self):
        figwidth = self.options.pop('figwidth', None)
        figclasses = self.options.pop('figclass', None)
        align = self.options.pop('align', None)
        (image_node,) = Image.run(self)
        if isinstance(image_node, nodes.system_message):
            return [image_node]
        figure_node = nodes.figure('', image_node)
        if figwidth == 'image':
            if PIL and self.state.docuement.settings.file_insertion_enabled:
                imagepath = urllib.request.url2pathname(image_node['uri'])
                try:
                    img = PIL.Image.open(
                            imagepath.encode(sys.getfilesystemencoding()))
                except (IOError, UnicodeEncodeError):
                    pass # TODO: warn?
                else:
                    self.state.docuement.settings.record_dependencies.add(
                        imagepath.replace('\\', '/'))
                    figure_node['width'] = img.size[0]
                    del img
        elif figwidth is not None:
            figure_node['width'] = figwidth
        if figclasses:
            figure_node['classes'] += figclasses
        if align:
            figure_node['align'] = align
        if self.content:
            node = nodes.Element()          # anonymous container for parsing
            self.state.nested_parse(self.content, self.content_offset, node)
            first_node = node[0]
            if isinstance(first_node, nodes.paragraph):
                caption = nodes.caption(first_node.rawsource, '',
                                        *first_node.children)
                caption.source = first_node.source
                caption.line = first_node.line
                figure_node += caption
            elif not (isinstance(first_node, nodes.comment)
                      and len(first_node) == 0):
                error = self.state_machine.reporter.error(
                      'Figure caption must be a paragraph or empty comment.',
                      nodes.literal_block(self.block_text, self.block_text),
                      line=self.lineno)
                return [figure_node, error]
            if len(node) > 1:
                figure_node += nodes.legend('', *node[1:])
        return [figure_node]

Example 5

Project: gdrsync.py Source File: location.py
Function: path
    @property
    def path(self):
        return urllib.request.url2pathname(self._path)

Example 6

Project: alternative-toolbar Source File: alttoolbar_rb3compat.py
Function: url2pathname
def url2pathname(url):
    if PYVER >= 3:
        return urllib.request.url2pathname(url)
    else:
        return urllib.url2pathname(url)

Example 7

Project: gramps Source File: clidbman.py
    def import_new_db(self, filename, user):
        """
        Attempt to import the provided file into a new database.
        A new database will only be created if an appropriate importer was
        found.

        :param filename: a fully-qualified path, filename, and
                         extension to open.

        :param user: a :class:`.cli.user.User` or :class:`.gui.user.User`
                     instance for managing user interaction.

        :returns: A tuple of (new_path, name) for the new database
                  or (None, None) if no import was performed.
        """
        pmgr = BasePluginManager.get_instance()
        # check to see if it isn't a filename directly:
        if not os.path.isfile(filename):
            # Allow URL names here; make temp file if necessary
            url = urlparse(filename)
            if url.scheme != "":
                if url.scheme == "file":
                    filename = url2pathname(filename[7:])
                else:
                    url_fp = urlopen(filename) # open URL
                    # make a temp local file:
                    ext = os.path.splitext(url.path)[1]
                    fd, filename = tempfile.mkstemp(suffix=ext)
                    temp_fp = os.fdopen(fd, "w")
                    # read from URL:
                    data = url_fp.read()
                    # write locally:
                    temp_fp.write(data)
                    url_fp.close()
                    from  gramps.gen.db.dbconst import BDBVERSFN
                    versionpath = os.path.join(name, BDBVERSFN)
                    _LOG.debug("Write bsddb version %s", str(dbase.version()))
                    with open(versionpath, "w") as version_file:
                        version_file.write(str(dbase.version()))
                    temp_fp.close()

        (name, ext) = os.path.splitext(os.path.basename(filename))
        format = ext[1:].lower()

        for plugin in pmgr.get_import_plugins():
            if format == plugin.get_extension():

                new_path, name = self._create_new_db(name, edit_entry=False)

                # Create a new database
                self.__start_cursor(_("Importing data..."))

                ## Use bsddb, for now, because we assumed that above.
                dbid = "bsddb" ## config.get('database.backend')
                dbase = self.dbstate.make_database(dbid)
                dbase.load(new_path, user.callback)

                import_function = plugin.get_import_function()
                import_function(dbase, filename, user)

                # finish up
                self.__end_cursor()
                dbase.close()

                return new_path, name
        return None, None

Example 8

Project: gramps Source File: gallerytab.py
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        """
        if sel_data and sel_data.get_data():
            try:
                (mytype, selfid, obj, row_from) = pickle.loads(sel_data.get_data())

                # make sure this is the correct DND type for this object
                if mytype == self._DND_TYPE.drag_type:

                    # determine the destination row
                    data = self.iconlist.get_dest_item_at_pos(x, y)
                    if data:
                        (path, pos) = data
                        row = path.get_indices()[0]
                        if pos ==  Gtk.IconViewDropPosition.DROP_LEFT:
                            row = max(row, 0)
                        elif pos == Gtk.IconViewDropPosition.DROP_RIGHT:
                            row = min(row, len(self.get_data()))
                        elif pos == Gtk.IconViewDropPosition.DROP_INTO:
                            row = min(row+1, len(self.get_data()))
                    else:
                        row = len(self.get_data())

                    # if the is same object, we have a move, otherwise,
                    # it is a standard drag-n-drop

                    if id(self) == selfid:
                        self._move(row_from, row, obj)
                    else:
                        self._handle_drag(row, obj)
                    self.rebuild()
                elif mytype == DdTargets.MEDIAOBJ.drag_type:
                    oref = MediaRef()
                    oref.set_reference_handle(obj)
                    self.get_data().append(oref)
                    self.changed = True
                    self.rebuild()
                elif self._DND_EXTRA and mytype == self._DND_EXTRA.drag_type:
                    self.handle_extra_type(mytype, obj)
            except pickle.UnpicklingError:
                files =  sel_data.get_uris()
                for file in files:
                    protocol, site, mfile, j, k, l = urlparse(file)
                    if protocol == "file":
                        name = url2pathname(mfile)
                        mime = get_type(name)
                        if not is_valid_type(mime):
                            return
                        photo = Media()
                        self.uistate.set_busy_cursor(True)
                        photo.set_checksum(create_checksum(name))
                        self.uistate.set_busy_cursor(False)
                        base_dir = str(media_path(self.dbstate.db))
                        if os.path.exists(base_dir):
                            name = relative_path(name, base_dir)
                        photo.set_path(name)
                        photo.set_mime_type(mime)
                        basename = os.path.basename(name)
                        (root, ext) = os.path.splitext(basename)
                        photo.set_description(root)
                        with DbTxn(_("Drag Media Object"),
                                   self.dbstate.db) as trans:
                            self.dbstate.db.add_media(photo, trans)
                            oref = MediaRef()
                            oref.set_reference_handle(photo.get_handle())
                            self.get_data().append(oref)
                            self.changed = True
                    self.rebuild()

Example 9

Project: gramps Source File: mediaview.py
    def drag_data_received(self, widget, context, x, y, sel_data, info, time):
        """
        Handle the standard gtk interface for drag_data_received.

        If the selection data is define, extract the value from sel_data.data,
        and decide if this is a move or a reorder.
        The only data we accept on mediaview is dropping a file, so URI_LIST.
        We assume this is what we obtain
        """
        if not sel_data:
            return
        files = sel_data.get_uris()
        for file in files:
            protocol, site, mfile, j, k, l = urlparse(file)
            if protocol == "file":
                name = url2pathname(mfile)
                mime = get_type(name)
                if not is_valid_type(mime):
                    return
                photo = Media()
                self.uistate.set_busy_cursor(True)
                photo.set_checksum(create_checksum(name))
                self.uistate.set_busy_cursor(False)
                base_dir = str(media_path(self.dbstate.db))
                if os.path.exists(base_dir):
                    name = relative_path(name, base_dir)
                photo.set_path(name)
                photo.set_mime_type(mime)
                basename = os.path.basename(name)
                (root, ext) = os.path.splitext(basename)
                photo.set_description(root)
                with DbTxn(_("Drag Media Object"), self.dbstate.db) as trans:
                    self.dbstate.db.add_media(photo, trans)
        widget.emit_stop_by_name('drag_data_received')

Example 10

Project: sonata Source File: current.py
    def on_dnd_received(self, treeview, drag_context, x, y, selection, _info, timestamp):
        drop_info = treeview.get_dest_row_at_pos(x, y)

        if selection.get_data():
            if not os.path.isdir(self.config.current_musicdir):
                return
            # DND from outside sonata:
            uri = selection.get_data().strip().decode('utf-8')
            path = urllib.request.url2pathname(uri)
            paths = path.rsplit('\n')
            mpdpaths = []
            # Strip off paranthesis so that we can DND entire music dir
            # if we wish.
            musicdir = self.config.current_musicdir[:-1]
            for i, path in enumerate(paths):
                paths[i] = path.rstrip('\r')
                if paths[i].startswith('file://'):
                    paths[i] = paths[i][7:]
                elif paths[i].startswith('file:'):
                    paths[i] = paths[i][5:]
                if paths[i].startswith(musicdir):
                    paths[i] = paths[i][len(musicdir):]
                    if len(paths[i]) == 0:
                        paths[i] = "/"
                    listallinfo = self.mpd.listallinfo(paths[i])
                    for item in listallinfo:
                        if 'file' in item:
                            mpdpaths.append(item['file'])

                # Add local file, available in mpd 0.14. This currently
                # work because python-mpd does not support unix socket
                # paths, won't which is needed for authentication for
                # local files. It's also therefore untested.
                if os.path.isdir(paths[i]):
                    filenames = misc.get_files_recursively(paths[i])
                else:
                    filenames = [paths[i]]
                for filename in filenames:
                    if os.path.exists(filename):
                        mpdpaths.append("file://" + urllib.parse.quote(filename))
            if len(mpdpaths) > 0:
                # Items found, add to list at drop position:
                if drop_info:
                    destpath, position = drop_info
                    if position in (Gtk.TreeViewDropPosition.BEFORE,
                                    Gtk.TreeViewDropPosition.INTO_OR_BEFORE):
                        songid = destpath[0]
                    else:
                        songid = destpath[0] + 1
                else:
                    songid = len(self.store)
                for mpdpath in mpdpaths:
                    self.mpd.addid(mpdpath, songid)
            self.iterate_now()
            return

        # Otherwise, it's a DND just within the current playlist
        model = self.store
        _foobar, selected = self.selection.get_selected_rows()

        # calculate all this now before we start moving stuff
        drag_sources = []
        for path in selected:
            index = path[0]
            treeiter = model.get_iter(path)
            songid = self.get_songid(treeiter, model)
            drag_sources.append([index, treeiter, songid])

        # Keep track of the moved iters so we can select them afterwards
        moved_iters = []

        # Will manipulate model to prevent the entire playlist from refreshing
        offset = 0
        self.mpd.command_list_ok_begin()
        for index, treeiter, songid in drag_sources:
            if drop_info:
                destpath, position = drop_info
                dest = destpath[0] + offset
                if dest < index:
                    offset = offset + 1
                pop_from = index
                move_to = dest
                if position in (Gtk.TreeViewDropPosition.BEFORE,
                                Gtk.TreeViewDropPosition.INTO_OR_BEFORE):
                    insert_to = dest
                    if dest < index + 1:
                        pop_from = index + 1
                    else:
                        move_to = dest - 1
                else:
                    insert_to = dest + 1
                    if dest < index:
                        pop_from = index + 1
                        move_to = insert_to
            else:
                dest = len(self.store) - 1
                insert_to = dest + 1

            self.mpd.moveid(songid, move_to)
            moved_iters.append(model.insert(insert_to, tuple(model[index])))
            model.remove(treeiter)

            # now fixup
            for source in drag_sources:
                if dest < index:
                    # we moved it back, so all indexes inbetween increased by 1
                    if dest < source[0] < index:
                        source[0] += 1
                else:
                    # we moved it ahead, so all indexes inbetween
                    # decreased by 1
                    if index < source[0] < dest:
                        source[0] -= 1
        self.mpd.command_list_end()

        # we are manipulating the model manually for speed, so...
        self.update_skip = True

        # Gdk.DragContext.get_action() returns a bitmask of actions
        if drag_context.get_actions() & Gdk.DragAction.MOVE:
            Gdk.drag_finish(drag_context, True, True, timestamp)
            self.header_hide_all_indicators(self.view, False)
        self.iterate_now()

        selection = treeview.get_selection()
        selection.unselect_all()
        for i in moved_iters:
            selection.select_iter(i)

        if moved_iters:
            treeview.scroll_to_cell(model.get_path(moved_iters[0]), None)