当前位置: 首页>>代码示例>>Python>>正文


Python datastore.write函数代码示例

本文整理汇总了Python中sugar.datastore.datastore.write函数的典型用法代码示例。如果您正苦于以下问题:Python write函数的具体用法?Python write怎么用?Python write使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了write函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: exportFile

 def exportFile(self, _widget, fancy, amount, dialog):
     fullPath= _widget.value;
     dialog.close()
     if self.script.journal:
         dsObject= datastore.create()
         print dir(dsObject.metadata)
         dsObject.metadata.get_dictionary().update(self.autogenerateMetadata())
         dsObject.metadata['title']= fullPath.actualValue
         if fancy == "Fancy":
             dsObject.metadata['mime_type'] = 'text/html'
         else:
             dsObject.metadata['mime_type'] = 'text/plain'
         fullPath = directories['instance'] + 'temp.bdw'
         self.script.export((directories['instance'] + 'temp.bdw', fancy, amount));
         dsObject.set_file_path(fullPath)
         datastore.write(dsObject)
     else:
         fileName, fileExtension= os.path.splitext(fullPath);
         if fancy == "Fancy" and fileExtension != ".html":
             fullPath+= ".html"
         elif fancy == "Plain" and fileExtension != ".txt":
             fullPath+= ".txt"
         if os.path.isfile(fullPath):
             self.confirmActionDialog(_("Overwrite?"),
                                     [ _("This file already exists:"),
                                       os.path.basename(fullPath),
                                       _("Are you sure you want to overwrite it?")],
                                     okayFunction= self.script.export, 
                                     arguments=(fullPath,fancy, amount));
         else:
             self.script.export((fullPath, fancy, amount));
开发者ID:acbart,项目名称:broadway.activity,代码行数:31,代码来源:filePanel.py

示例2: __init__

    def __init__(self, handle):
    
        activity.Activity.__init__(self, handle)
        """ Create the official Sugar toolbox at the top of the screen"""
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()
        
        file_location = activity.get_activity_root() + \
                        "/data/reckonprimer_report.txt" 
        file_handle = open(file_location, 'w')
        file_handle.write("Report: " + profile.get_nick_name() + \
                          strftime(" %Y-%m-%d %H:%M:%S") + "\n")        
        file_handle.close()
        
        title = "Report: " + profile.get_nick_name() + \
                strftime(" %Y-%m-%d %H:%M:%S")
        mime = "text/plain"
        file_path = activity.get_activity_root() + \
                    "/data/reckonprimer_report.txt"
        favorite = "1"
        tags = "ReckonPrimer"
        
        journal_object = datastore.create()
        journal_object.metadata['title'] = title
        journal_object.metadata['mime_type'] = mime
        journal_object.file_path = file_path  
        journal_object.metadata['keep'] = favorite
        journal_object.metadata['tags'] = tags
        journal_object.metadata['icon-color'] = '#AFD600,#5B615C' 
        datastore.write( journal_object )
        journal_object.destroy()

        self.run_session()
开发者ID:mifix,项目名称:ReckonPrimer,代码行数:34,代码来源:ReckonPrimerActivity.py

示例3: _save_recording

 def _save_recording(self):
     if os.path.exists(os.path.join(self.datapath, 'output.ogg')):
         _logger.debug('Saving recording to Journal...')
         obj_id = self._get_audio_obj_id()
         copyfile(os.path.join(self.datapath, 'output.ogg'),
                  os.path.join(self.datapath, '%s.ogg' % (obj_id)))
         dsobject = self._search_for_audio_note(obj_id)
         if dsobject is None:
             dsobject = datastore.create()
         if dsobject is not None:
             _logger.debug(self.dsobjects[self.i].metadata['title'])
             dsobject.metadata['title'] = _('Audio recording by %s') % \
                 (self.metadata['title'])
             dsobject.metadata['icon-color'] = \
                 profile.get_color().to_string()
             dsobject.metadata['tags'] = obj_id
             dsobject.metadata['mime_type'] = 'audio/ogg'
             dsobject.set_file_path(
                 os.path.join(self.datapath, '%s.ogg' % (obj_id)))
             datastore.write(dsobject)
             dsobject.destroy()
         self._add_playback_button(
             profile.get_nick_name(), self.colors,
             os.path.join(self.datapath, '%s.ogg' % (obj_id)))
         if hasattr(self, 'chattube') and self.chattube is not None:
             self._share_audio()
     else:
         _logger.debug('Nothing to save...')
     return
开发者ID:walterbender,项目名称:bulletinboard,代码行数:29,代码来源:BBoardActivity.py

示例4: _install_update

    def _install_update(self, bundle_update, local_file_path):

        total = self._total_bundles_to_update
        current = total - len(self._bundles_to_update) - 0.5

        self.emit('progress', UpdateModel.ACTION_UPDATING,
                  bundle_update.bundle.get_name(),
                  current, total)

        # TODO: Should we first expand the zip async so we can provide progress
        # and only then copy to the journal?
        jobject = datastore.create()
        try:
            title = '%s-%s' % (bundle_update.bundle.get_name(),
                               bundle_update.version)
            jobject.metadata['title'] = title
            jobject.metadata['mime_type'] = ActivityBundle.MIME_TYPE
            jobject.file_path = local_file_path
            datastore.write(jobject, transfer_ownership=True)
        finally:
            jobject.destroy()

        self.emit('progress', UpdateModel.ACTION_UPDATING,
                  bundle_update.bundle.get_name(),
                  current + 0.5, total)

        if self._bundles_to_update:
            # do it in idle so the UI has a chance to refresh
            gobject.idle_add(self._download_next_update)
开发者ID:nemesiscodex,项目名称:JukyOS-sugar,代码行数:29,代码来源:model.py

示例5: myblock

def myblock(tw, title):
    ''' Save heap to journal (Sugar only) '''

    import os.path
    from gettext import gettext as _

    from sugar.activity import activity
    from sugar.datastore import datastore
    from sugar import profile

    from TurtleArt.tautils import get_path, data_to_file

    # Save JSON-encoded heap to temporary file
    heap_file = os.path.join(get_path(activity, 'instance'),
                             str(title) + '.txt')
    data_to_file(tw.lc.heap, heap_file)

    # Create a datastore object
    dsobject = datastore.create()

    # Write any metadata (specifically set the title of the file
    #                     and specify that this is a plain text file).
    dsobject.metadata['title'] = str(title)
    dsobject.metadata['icon-color'] = profile.get_color().to_string()
    dsobject.metadata['mime_type'] = 'text/plain'
    dsobject.set_file_path(heap_file)
    datastore.write(dsobject)
    dsobject.destroy()
开发者ID:sugarlabs,项目名称:activity-turtle-flags,代码行数:28,代码来源:save_heap_to_journal_entry.py

示例6: __activate_cb

    def __activate_cb(self, menu_item, activity, abi, format):
        logger.debug("exporting file: %r" % format)

        exp_props = format["exp_props"]

        # special case HTML export to set the activity name as the HTML title
        if format["mime_type"] == "text/html":
            exp_props += " title:" + activity.metadata["title"] + ";"

        # create a new journal item
        fileObject = datastore.create()
        act_meta = activity.metadata
        fileObject.metadata["title"] = act_meta["title"] + " (" + format["jpostfix"] + ")"
        fileObject.metadata["title_set_by_user"] = act_meta["title_set_by_user"]
        fileObject.metadata["mime_type"] = format["mime_type"]
        fileObject.metadata["fulltext"] = abi.get_content(extension_or_mimetype=".txt")[:3000]

        fileObject.metadata["icon-color"] = act_meta["icon-color"]
        fileObject.metadata["activity"] = act_meta["activity"]
        fileObject.metadata["keep"] = act_meta["keep"]

        preview = activity.get_preview()
        if preview is not None:
            fileObject.metadata["preview"] = dbus.ByteArray(preview)

        fileObject.metadata["share-scope"] = act_meta["share-scope"]

        # write out the document contents in the requested format
        fileObject.file_path = os.path.join(activity.get_activity_root(), "instance", "%i" % time.time())
        abi.save("file://" + fileObject.file_path, format["mime_type"], exp_props)

        # store the journal item
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
开发者ID:Daksh,项目名称:devtutor,代码行数:35,代码来源:widgets.py

示例7: install

    def install(self):
        if os.environ.has_key('SUGAR_ACTIVITY_ROOT'):
            install_dir = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'], 'instance')
        else:
            install_dir = tempfile.gettempdir()
        uid = self.get_entry_id()
        bundle_dir = os.path.join(install_dir, uid)
        self._unzip(install_dir)
        try:
            metadata = self.get_metadata()
            jobject = datastore.create()
            try:
                for key, value in metadata.iteritems():
                    jobject.metadata[key] = value

                preview = self.get_preview()
                if preview != '':
                    jobject.metadata['preview'] = dbus.ByteArray(preview)
                jobject.metadata['uid'] = ''

                if jobject.metadata.has_key('mountpoint'):
                    del jobject.metadata['mountpoint']

                os.chmod(bundle_dir, RWXR_XR_X)

                if( os.path.exists( os.path.join(bundle_dir, uid) ) ):
                    jobject.file_path = os.path.join(bundle_dir, uid)
                    os.chmod(jobject.file_path, RW_R__R__)

                datastore.write(jobject)
            finally:
                jobject.destroy()
        finally:
            shutil.rmtree(bundle_dir, ignore_errors=True)
开发者ID:jlew,项目名称:xo-file-distro,代码行数:34,代码来源:journalentrybundle.py

示例8: open_url

 def open_url(self, url):
     """Ask the journal to open an URL for us."""
     from sugar import profile
     from shutil import rmtree
     from sugar.datastore import datastore
     from sugar.activity.activity import show_object_in_journal
     from tempfile import mkdtemp
     tmpfolder = mkdtemp('.tmp', 'url', os.path.join(self.get_activity_root(), 'instance'))
     tmpfilepath = os.path.join(tmpfolder, 'url')
     try:
         tmpfile = open(tmpfilepath, 'w')
         tmpfile.write(url)
         tmpfile.close()
         os.chmod(tmpfolder, 0755)
         os.chmod(tmpfilepath, 0755)
         jobject = datastore.create()
         metadata = {
             'title': url,
             'title_set_by_user': '1',
             'buddies': '',
             'preview': '',
             'icon-color': profile.get_color().to_string(),
             'mime_type': 'text/uri-list',
         }
         for k, v in metadata.items():
             jobject.metadata[k] = v # the dict.update method is missing =(
         jobject.file_path = tmpfilepath
         datastore.write(jobject)
         show_object_in_journal(jobject.object_id)
         jobject.destroy()
     finally:
         rmtree(tmpfilepath, ignore_errors=True) # clean up!
开发者ID:sugarlabs,项目名称:Frotz,代码行数:32,代码来源:frotz.py

示例9: __export_png_cb

    def __export_png_cb(self, event):
        x, y, w, h, bitdepth = self._main_area.window.get_geometry()
        cmap = self._main_area.window.get_colormap()
        maxx, maxy = self._main_area.get_max_area()
        true_width = int(maxx)
        true_height = int(maxy)

        # Create the new journal entry
        fileObject = datastore.create()
        act_meta = self.metadata
        fileObject.metadata['title'] = act_meta['title'] + ' (PNG)'
        fileObject.metadata['title_set_by_user'] = \
            act_meta['title_set_by_user']
        fileObject.metadata['mime_type'] = 'image/png'

        fileObject.metadata['icon-color'] = act_meta['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        pixmap = gtk.gdk.Pixmap(None, true_width, true_height, bitdepth)
        pixmap.set_colormap(cmap)
        self._main_area.export(pixmap.cairo_create(), true_width, true_height,
                               False)

        pb = gtk.gdk.Pixbuf.get_from_drawable(
            gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, true_width,
                           true_height),
            pixmap, gtk.gdk.colormap_get_system(), 0, 0, 0, 0, true_width,
            true_height)

        pb.save(filename, 'png')
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
开发者ID:Daksh,项目名称:Labyrinth,代码行数:34,代码来源:labyrinthactivity.py

示例10: __notify_state_cb

 def __notify_state_cb(self, file_transfer, pspec):
     if file_transfer.props.state == filetransfer.FT_STATE_OPEN:
         logging.debug('__notify_state_cb OPEN')
         self._ds_object.metadata['title'] = file_transfer.title
         self._ds_object.metadata['description'] = file_transfer.description
         self._ds_object.metadata['progress'] = '0'
         self._ds_object.metadata['keep'] = '0'
         self._ds_object.metadata['buddies'] = ''
         self._ds_object.metadata['preview'] = ''
         self._ds_object.metadata['icon-color'] = \
                 file_transfer.buddy.props.color.to_string()
         self._ds_object.metadata['mime_type'] = file_transfer.mime_type
     elif file_transfer.props.state == filetransfer.FT_STATE_COMPLETED:
         logging.debug('__notify_state_cb COMPLETED')
         self._ds_object.metadata['progress'] = '100'
         self._ds_object.file_path = file_transfer.destination_path
         datastore.write(self._ds_object, transfer_ownership=True,
                         reply_handler=self.__reply_handler_cb,
                         error_handler=self.__error_handler_cb)
     elif file_transfer.props.state == filetransfer.FT_STATE_CANCELLED:
         logging.debug('__notify_state_cb CANCELLED')
         object_id = self._ds_object.object_id
         if object_id is not None:
             self._ds_object.destroy()
             datastore.delete(object_id)
             self._ds_object = None
开发者ID:nemesiscodex,项目名称:JukyOS-sugar,代码行数:26,代码来源:activitiestray.py

示例11: __export_pdf_cb

    def __export_pdf_cb(self, event):
        maxx, maxy = self._main_area.get_max_area()
        true_width = int(maxx)
        true_height = int(maxy)

        # Create the new journal entry
        fileObject = datastore.create()
        act_meta = self.metadata
        fileObject.metadata['title'] = act_meta['title'] + ' (PDF)'
        fileObject.metadata['title_set_by_user'] = \
            act_meta['title_set_by_user']
        fileObject.metadata['mime_type'] = 'application/pdf'

        # TODO: add text thoughts into fulltext metadata
        # fileObject.metadata['fulltext'] = ...

        fileObject.metadata['icon-color'] = act_meta['icon-color']
        fileObject.file_path = os.path.join(self.get_activity_root(),
                                            'instance', '%i' % time.time())
        filename = fileObject.file_path
        surface = cairo.PDFSurface(filename, true_width, true_height)
        cairo_context = cairo.Context(surface)
        context = pangocairo.CairoContext(cairo_context)
        self._main_area.export(context, true_width, true_height, False)
        surface.finish()
        datastore.write(fileObject, transfer_ownership=True)
        fileObject.destroy()
        del fileObject
开发者ID:Daksh,项目名称:Labyrinth,代码行数:28,代码来源:labyrinthactivity.py

示例12: saveFile

 def saveFile(self, _widget):
     fullPath= _widget.value;
     if self.script.journal:
         if type(fullPath.actualValue) == str:
             dsObject= datastore.create()
             print dir(dsObject.metadata)
             dsObject.metadata.get_dictionary().update(self.autogenerateMetadata())
             dsObject.metadata['title']= fullPath.actualValue
             self.script.saveFile(directories['instance'] + 'temp.bdw')
             dsObject.set_file_path(self.script.filepath)
             datastore.write(dsObject)
             self.script.filepath = dsObject
         else:
             dsObject= fullPath.actualValue
             self.script.saveFile(directories['instance'] + 'temp.bdw')
             dsObject.set_file_path(self.script.filepath)
             datastore.write(dsObject)
             self.script.filepath = fullPath.actualValue
         self.refreshPanel();
     else:
         fileName, fileExtension= os.path.splitext(fullPath);
         if fileExtension != information['filetype']:
             fullPath+= information['filetype'];
         if os.path.isfile(fullPath):
             self.confirmActionDialog(_("Overwrite?"),
                                     [ _("This file already exists:"),
                                       os.path.basename(fullPath),
                                       _("Are you sure you want to overwrite it?")],
                                     okayFunction= self.script.saveFile, 
                                     arguments=fullPath);
         else:
             self.script.saveFile(fullPath);
开发者ID:acbart,项目名称:broadway.activity,代码行数:32,代码来源:filePanel.py

示例13: _file_part_receiver

    def _file_part_receiver(self, target, filename, part, numparts,
                            bytes, title=None, color=None, sender=None):
        # ignore my own signal
        if sender == self._tube.get_unique_name():
            return
        
        if not (target == 'all' or target == self._tube.get_unique_name()):
            return
        
        # first chunk
        if part == 1:
            tmp_root = join(environ['SUGAR_ACTIVITY_ROOT'], 'instance')
            temp_dir = tempfile.mkdtemp(dir=tmp_root)
            chmod(temp_dir, 0777)
            self.temp_file = join(temp_dir, 'game.zip')
            self.files[filename] = self.temp_file
            self.f = open(self.temp_file, 'a+b')
        
        self.f.write(bytes)
        
        percentage = int(float(part) / float(numparts) * 100.0)
        self.game.set_load_mode(_('Receiving game') + ': '
                                + str(percentage) + '% ' + _('done') + '.')

        # last chunk
        if part == numparts:
            self.f.close()   
            #file = self.files[filename]
            # Saves the zip in datastore
            gameObject = datastore.create()
            gameObject.metadata['title'] = title
            gameObject.metadata['mime_type'] = 'application/x-memorize-project'
            gameObject.metadata['icon-color'] = color
            gameObject.file_path = self.temp_file
            datastore.write(gameObject)
开发者ID:pmoleri,项目名称:memorize-accesible,代码行数:35,代码来源:messenger.py

示例14: generate_bundle

def generate_bundle(nick, new_basename):
    """Generate a new .xo bundle for the activity and copy it into the
    Journal.

    """
    new_activity_name = _customize_activity_info(
        nick, new_basename)

    user_activities_path = get_user_activities_path()
    if os.path.exists(os.path.join(user_activities_path, new_basename,
                                   'dist')):
        for path in glob.glob(os.path.join(user_activities_path, new_basename,
                                           'dist', '*')):
            os.remove(path)

    config = bundlebuilder.Config(source_dir=os.path.join(
            user_activities_path, new_basename),
            dist_name='%s-1.xo' % (new_activity_name))
    bundlebuilder.cmd_dist_xo(config, None)

    dsobject = datastore.create()
    dsobject.metadata['title'] = '%s-1.xo' % (new_activity_name)
    dsobject.metadata['mime_type'] = 'application/vnd.olpc-sugar'
    dsobject.set_file_path(os.path.join(
            user_activities_path, new_basename, 'dist',
            '%s-1.xo' % (new_activity_name)))
    datastore.write(dsobject)
    dsobject.destroy()
开发者ID:nemesiscodex,项目名称:JukyOS-sugar,代码行数:28,代码来源:customizebundle.py

示例15: _license_cb

 def _license_cb(self,widget,uri):
     if not self._jobject:
         ll.set_default(uri)
         self.refresh()
     else:
         ll.write(self._jobject.get_file_path(),uri)
         self._jobject.metadata['license'] = uri
         datastore.write(self._jobject, update_mtime=False)
开发者ID:cc-archive,项目名称:liblicense-sugar,代码行数:8,代码来源:sugar.py


注:本文中的sugar.datastore.datastore.write函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。