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


Python datastore.write函数代码示例

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


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

示例1: _comment_activate_cb

    def _comment_activate_cb(self, entry):
        text = entry.props.text
        if not "comments" in self._reflection.data:
            self._reflection.data["comments"] = []
        data = {
            "nick": profile.get_nick_name(),
            "color": self._reflection.activity.fg_color.get_html(),
            "comment": text,
        }
        self._reflection.data["comments"].append(data)
        self.add_new_comment(data)
        # Send the comment
        if self._reflection.activity.sharing:
            self._reflection.activity.send_event(
                "%s|%s|%s|%s|%s"
                % (COMMENT_CMD, self._reflection.data["obj_id"], data["nick"], data["color"], data["comment"])
            )
        entry.set_text("")

        # Update journal entry
        dsobj = datastore.get(self._reflection.data["obj_id"])
        if "comments" in dsobj.metadata:
            data = json.loads(dsobj.metadata["comments"])
        else:
            data = []
        data.append({"from": profile.get_nick_name(), "message": text, "icon-color": profile.get_color().to_string()})
        dsobj.metadata["comments"] = json.dumps(data)
        datastore.write(
            dsobj,
            update_mtime=False,
            reply_handler=self.datastore_write_cb,
            error_handler=self.datastore_write_error_cb,
        )
开发者ID:samdroid-apps,项目名称:reflect,代码行数:33,代码来源:reflectwindow.py

示例2: _process_tags

    def _process_tags(self, text_buffer, text):
        """ process tag data from textview """
        self._reflection.data["tags"] = []
        label = ""
        tags = text.split()
        for tag in tags:
            if len(label) > 0:
                label += ", "
            tag = tag.rstrip(",")
            tag = tag.rstrip(";")
            if tag[0] == "#":
                self._reflection.data["tags"].append(tag)
                label += tag
            else:
                self._reflection.data["tags"].append("#" + tag)
                label += "#" + tag
        text_buffer.set_text(label.replace("\12", ""))
        if self._reflection.activity.sharing:
            data = json.dumps(self._reflection.data["tags"])
            self._reflection.activity.send_event("%s|%s|%s" % (TAG_CMD, self._reflection.data["obj_id"], data))
        self._reflection.set_modification_time()

        # Update journal entry
        dsobj = datastore.get(self._reflection.data["obj_id"])
        logging.error("setting tags to %s" % label)
        dsobj.metadata["tags"] = label
        datastore.write(
            dsobj,
            update_mtime=False,
            reply_handler=self.datastore_write_cb,
            error_handler=self.datastore_write_error_cb,
        )
开发者ID:samdroid-apps,项目名称:reflect,代码行数:32,代码来源:reflectwindow.py

示例3: _photo_created_cb

    def _photo_created_cb(self, fb_photo, fb_object_id, tmp_file):
        logging.debug("_photo_created_cb")

        if os.path.exists(tmp_file):
            os.unlink(tmp_file)

        metadata = self._get_metadata()

        comment = ''
        if 'title' in metadata:
            comment += '%s:' % str(metadata['title'])
        if 'description' in metadata:
            comment += str(metadata['description'])

        fb_photo.connect('comment-added', self._comment_added_cb)
        fb_photo.connect('comment-add-failed', self._comment_add_failed_cb)
        fb_photo.add_comment(comment)

        try:
            ds_object = datastore.get(metadata['uid'])
            ds_object.metadata['fb_object_id'] = fb_object_id
            datastore.write(ds_object, update_mtime=False)
        except Exception as ex:
            logging.debug("_photo_created_cb failed to write to datastore: " %
                          str(ex))
开发者ID:walterbender,项目名称:facebook,代码行数:25,代码来源:account.py

示例4: insert_comment

 def insert_comment(self, obj_id, comment):
     for item in self._reflections:
         if item.obj_id == obj_id:
             item.graphics.add_new_comment(comment)
             item.graphics.notify_button.show()
             # Update journal entry
             if obj_id[0:4] == "obj-":
                 break
             try:
                 dsobj = datastore.get(obj_id)
             except Exception as e:
                 logging.error("Could not open %s: %e" % (obj_id, e))
                 break
             if "comments" in dsobj.metadata:
                 data = json.loads(dsobj.metadata["comments"])
             else:
                 data = []
             data.append(
                 {
                     "from": comment["nick"],
                     "message": comment["comment"],
                     "icon-color": "%s,%s" % (comment["color"], comment["color"]),
                 }
             )
             dsobj.metadata["comments"] = json.dumps(data)
             datastore.write(
                 dsobj,
                 update_mtime=False,
                 reply_handler=self.datastore_write_cb,
                 error_handler=self.datastore_write_error_cb,
             )
             break
开发者ID:samdroid-apps,项目名称:reflect,代码行数:32,代码来源:reflectwindow.py

示例5: do_drag_data_get

    def do_drag_data_get(self, path, selection):
        data = self.get_iter(path)
        mime_type = self.get_value(data, 13)
        fileid = self.get_value(data, 14)
        title = self.get_value(data, 15)
        data = self._account.download_file(fileid, self._display_alert)

        fd, file_path = tempfile.mkstemp(dir="/tmp/")
        os.close(fd)

        if data[0]:
            f = open(file_path, 'w')
            f.write(data[0])
            f.close()

        jobject = datastore.create()
        jobject.metadata['title'] = title
        jobject.metadata['icon-color'] = profile.get_color().to_string()
        jobject.metadata['mime_type'] = mime_type
        if data[1]:
            jobject.metadata['activity'] = data[1]

        if data[0]:
            jobject.file_path = file_path
        datastore.write(jobject)
        self._load_files()
        self._journal_button.set_active(True)
        self._listview.refresh()
开发者ID:i5o,项目名称:sugar-gdrive,代码行数:28,代码来源:account.py

示例6: _fb_comments_downloaded_cb

    def _fb_comments_downloaded_cb(self, fb_photo, comments):
        logging.debug('_fb_comments_downloaded_cb')

        ds_object = datastore.get(self._metadata['uid'])
        if not COMMENTS in ds_object.metadata:
            ds_comments = []
        else:
            ds_comments = json.loads(ds_object.metadata[COMMENTS])
        if not COMMENT_IDS in ds_object.metadata:
            ds_comment_ids = []
        else:
            ds_comment_ids = json.loads(ds_object.metadata[COMMENT_IDS])
        new_comment = False
        for comment in comments:
            if comment['id'] not in ds_comment_ids:
                # TODO: get avatar icon and add it to icon_theme
                ds_comments.append({'from': comment['from'],
                                    'message': comment['message'],
                                    'icon': 'facebook-share'})
                ds_comment_ids.append(comment['id'])
                new_comment = True
        if new_comment:
            ds_object.metadata[COMMENTS] = json.dumps(ds_comments)
            ds_object.metadata[COMMENT_IDS] = json.dumps(ds_comment_ids)
            self.emit('comments-changed', ds_object.metadata[COMMENTS])

        datastore.write(ds_object, update_mtime=False)
开发者ID:tchx84,项目名称:facebook,代码行数:27,代码来源:account.py

示例7: update_entry

    def update_entry(self):
        needs_update = False
        
        if self.selected_journal_entry is None:
            return

        object_id = self.selected_journal_entry.object_id
        jobject = datastore.get(object_id)
        
        old_title = jobject.metadata.get('title', None)
        if old_title != self.title_entry.props.text:
            jobject.metadata['title'] = self.title_entry.props.text
            jobject.metadata['title_set_by_user'] = '1'
            self.update_log_entries += '\n' + _('Entry title changed to %s') % self.title_entry.props.text
            needs_update = True

        old_tags = jobject.metadata.get('tags', None)
        new_tags = self.tags_textview.props.buffer.props.text
        if old_tags != new_tags:
            jobject.metadata['tags'] = new_tags
            self.update_log_entries += '\n' + _('Entry %s tags updated.') % self.title_entry.props.text
            needs_update = True

        old_description = jobject.metadata.get('description', None)
        new_description = self.description_textview.props.buffer.props.text
        if old_description != new_description:
            jobject.metadata['description'] = new_description
            self.update_log_entries += '\n' + _('Entry %s description updated.') % self.title_entry.props.text
            needs_update = True

        if needs_update:
            datastore.write(jobject, update_mtime=False,
                            reply_handler=self.datastore_write_cb,
                            error_handler=self.datastore_write_error_cb)
        self.btn_save.props.sensitive = False
开发者ID:leonardcj,项目名称:sugar-commander,代码行数:35,代码来源:sugarcommander.py

示例8: create_journal_entry

 def create_journal_entry(self,  widget,  data=None):
     filename = self._filechooser.get_filename()
     journal_entry = datastore.create()
     journal_entry.metadata['title'] = self.make_new_filename(filename)
     journal_entry.metadata['title_set_by_user'] = '1'
     journal_entry.metadata['keep'] = '0'
     file_mimetype = mime.get_for_file(filename)
     if not file_mimetype is None:
         journal_entry.metadata['mime_type'] = file_mimetype
     journal_entry.metadata['buddies'] = ''
     if file_mimetype.startswith('image/')  and file_mimetype != 'image/vnd.djvu':
         preview = self.create_preview_metadata(filename)
     elif file_mimetype  == 'application/x-cbz':
         fname = self.extract_image(filename)
         preview = self.create_preview_metadata(fname)
         os.remove(fname)
     else:
         preview = ''
     if not preview  == '':
         journal_entry.metadata['preview'] =  dbus.ByteArray(preview)
     else:
         journal_entry.metadata['preview'] =  ''
         
     journal_entry.file_path = filename
     datastore.write(journal_entry)
     self.update_log_entries += '\n' + _('File %s copied to the Journal.') % filename
     self.alert(_('Success'),  _('%s added to Journal.') 
                 % self.make_new_filename(filename))
开发者ID:leonardcj,项目名称:sugar-commander,代码行数:28,代码来源:sugarcommander.py

示例9: _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 target != self._tube.get_unique_name() and target != 'all':
            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:leonardcj,项目名称:memorize-activity,代码行数:35,代码来源:messenger.py

示例10: resize_button_press_event_cb

    def resize_button_press_event_cb(self, entry, event):
        jobject = self.selected_journal_entry
        filename = jobject.get_file_path()
        im = pygame.image.load(filename)
        image_width, image_height = im.get_size()
        resize_to_width = int(self.resize_width_entry.get_text())
        if (image_width < resize_to_width):
            self.alert(_('Error'),  _('Image cannot be made larger, only smaller.')) 
            return
        tempfile = os.path.join(self.get_activity_root(), 'instance',
                            'tmp%i' % time.time())
        try:
            scaled_pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(filename, resize_to_width, ARBITRARY_LARGE_HEIGHT)
            scaled_pixbuf.save(tempfile, "jpeg", {"quality":"%d" % JPEG_QUALITY})
        except:
            print 'File could not be converted'
            return

        jobject.file_path = tempfile
        jobject.metadata['mime_type'] = 'image/jpeg'
        im = pygame.image.load(tempfile)
        image_width, image_height = im.get_size()
        self.dimension_label.set_text(str(image_width) + "x" + str(image_height))
        self.dimension_label.show()
        datastore.write(jobject, update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
        title = jobject.metadata.get('title', None)
        self.update_log_entries += '\n' + _('Entry %s resized.') % title
开发者ID:leonardcj,项目名称:sugar-commander,代码行数:29,代码来源:sugarcommander.py

示例11: take_screenshot

    def take_screenshot(self, capture_count=1):
        ''' Take a screenshot and save to the Journal '''
        tmp_file_path = os.path.join(
            os.environ['SUGAR_ACTIVITY_ROOT'], 'instance',
            'screen_capture_' + str(capture_count) + '.png')

        window = self.activity.wave.get_window()
        width, height = window.get_width(), window.get_height()
        surface = Gdk.Window.create_similar_surface(window,
                                                    cairo.CONTENT_COLOR,
                                                    width, height)
        cr = cairo.Context(surface)
        Gdk.cairo_set_source_window(cr, window, 0, 0)
        cr.paint()
        surface.write_to_png(tmp_file_path)

        if os.path.exists(tmp_file_path):
            dsobject = datastore.create()
            try:
                dsobject.metadata['title'] = '%s %d' % (_('Waveform'),
                                                        capture_count)
                dsobject.metadata['keep'] = '0'
                dsobject.metadata['buddies'] = ''
                dsobject.metadata['preview'] = self._get_preview_data(surface)
                dsobject.metadata['icon-color'] = self.activity.icon_colors
                dsobject.metadata['mime_type'] = 'image/png'
                dsobject.set_file_path(tmp_file_path)
                datastore.write(dsobject)
            finally:
                dsobject.destroy()
                del dsobject
            os.remove(tmp_file_path)
            return True
        return False
开发者ID:sugarlabs,项目名称:Measure,代码行数:34,代码来源:journal.py

示例12: __export_as_abiword_cb

    def __export_as_abiword_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = \
            _('{} as Write document').format(self.metadata['title'])
        jobject.metadata['mime_type'] = 'application/x-abiword'
        preview = self.get_preview()
        if preview is not None:
            jobject.metadata['preview'] = dbus.ByteArray(preview)

        path = os.path.join(self.get_activity_root(),
                            'instance', str(time.time()))
        with open(path, 'w') as f:
            f.write('<?xml version="1.0" encoding="UTF-8"?>\n<abiword>\n'
                    '<section>')
            entries = []
            for item in self._main_list.all():
                markup = item[self._main_list.COLUMN_TEXT]
                abiword = '<p><c>{}</c></p>'.format(markup) \
                    .replace('<b>', '<c props="font-weight:bold">') \
                    .replace('<i>', '<c props="font-style:italic;'
                             ' font-weight:normal">') \
                    .replace('</b>', '</c>').replace('</i>', '</c>')
                entries.append(abiword)
            f.write('\n<p><c></c></p>\n'.join(entries))
            f.write('</section>\n</abiword>')
        jobject.file_path = path

        datastore.write(jobject, transfer_ownership=True)
        self._journal_alert(jobject.object_id, _('Success'), _('Your'
                            ' Bibliography was saved to the journal as a Write'
                            ' document'))
        jobject.destroy()
        del jobject
开发者ID:AbrahmAB,项目名称:bibliography-activity,代码行数:33,代码来源:activity.py

示例13: __export_as_html_cb

    def __export_as_html_cb(self, button):
        jobject = datastore.create()
        jobject.metadata['title'] = \
            _('{} as HTML').format(self.metadata['title'])
        jobject.metadata['mime_type'] = 'text/html'
        preview = self.get_preview()
        if preview is not None:
            jobject.metadata['preview'] = dbus.ByteArray(preview)

        # write out the document contents in the requested format
        path = os.path.join(self.get_activity_root(),
                            'instance', str(time.time()))
        with open(path, 'w') as f:
            f.write('''<html>
                         <head>
                           <title>{title}</title>
                         </head>

                         <body>
                           <h1>{title}</h1>
                    '''.format(title=jobject.metadata['title']))
            for item in self._main_list.all():
                f.write('<p>{}</p>'.format(
                    item[self._main_list.COLUMN_TEXT]))
            f.write('''
                         </body>
                       </html>
                    ''')
        jobject.file_path = path

        datastore.write(jobject, transfer_ownership=True)
        self._journal_alert(jobject.object_id, _('Success'), _('Your'
                            ' Bibliography was saved to the journal as HTML'))
        jobject.destroy()
        del jobject
开发者ID:AbrahmAB,项目名称:bibliography-activity,代码行数:35,代码来源:activity.py

示例14: export_font

    def export_font(self):
        """
        Export the current font loaded in globals.FONT as a .otf file.

        The file will be saved in the activity data folder
        """
        # create the file path

        file_path =\
            os.path.join(self.get_activity_root(),
                         'data', '%s.otf' % self.get_title)
        # save the otf
        globals.FONT.export_binary(file_path)

        # create a journal entry
        jobject = datastore.create()
        jobject.metadata['icon-color'] = profile.get_color().to_string()
        jobject.metadata['mime_type'] = 'application/x-font-opentype'
        jobject.metadata['title'] = '%s.otf' % self.get_title
        jobject.file_path = file_path
        datastore.write(jobject, transfer_ownership=True)
        self._object_id = jobject.object_id

        success_title = 'Success'
        success_msg = 'A OTF Font file was created in the Journal'
        self._show_journal_alert(_(success_title), _(success_msg))
开发者ID:sugarlabs,项目名称:edit-fonts-activity,代码行数:26,代码来源:EditFonts.py

示例15: _process_tags

    def _process_tags(self, text_buffer, text):
        ''' process tag data from textview '''
        self._reflection.data['tags'] = []
        label = ''
        tags = text.split()
        for tag in tags:
            if len(label) > 0:
                label += ', '
            tag = tag.rstrip(',')
            tag = tag.rstrip(';')
            if tag[0] == '#':
                self._reflection.data['tags'].append(tag)
                label += tag
            else:
                self._reflection.data['tags'].append('#' + tag)
                label += '#' + tag
        text_buffer.set_text(label.replace('\12', ''))
        if self._reflection.activity.sharing:
            data = json.dumps(self._reflection.data['tags'])
            self._reflection.activity.send_event(TAG_CMD,
                {"obj_id": self._refelection.data["ob_id"],
                 "reflection": data})
        self._reflection.set_modification_time()

        # Update journal entry
        dsobj = datastore.get(self._reflection.data['obj_id'])
        logging.error('setting tags to %s' % label)
        dsobj.metadata['tags'] = label
        datastore.write(dsobj,
                        update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
开发者ID:AbrahmAB,项目名称:reflect,代码行数:32,代码来源:reflectwindow.py


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