• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python storage.Storage类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: add

    def add(self, item):
        bookmark = self.find(item)

        if not bookmark:
            Storage.add(self, item)

            self.save()
开发者ID:shvets,项目名称:AudioBoo.bundle,代码行数:7,代码来源:media_info_storage.py


示例2: rooms_occupied_by

	def rooms_occupied_by(self, people):
		s = Storage(self.name, self.token, True)
		room_numbers, rooms, person_names, persons, current_timestamp = s.get_stats()
		log = s.get_log()

		people_wanted = { (t[1]+name):True for t, name in people }
		rooms = {}
		result = {}

		for event in log:
			if not event.who in people_wanted or event.room == -1:
				continue

			if event.action == 'A':
				if event.room in rooms:
					people_preset = rooms[event.room]
				else:
					people_present = {}
					rooms[event.room] = people_present

				people_present[event.who] = True
				if people_present == people_wanted:
					result[event.room] = True

			elif event.action == 'L':
				if event.who in rooms[event.room]:
					rooms[event.room].pop(event.who)

		if len(result) == 0:
			return

		result = [e for e in result.keys()]
		result.sort()
		result2 = [str(e) for e in result]
		print(','.join(result2))
开发者ID:rndCombo,项目名称:contestants_code_BIBIFI,代码行数:35,代码来源:log.py


示例3: read_config

def read_config(config_file):
    '''Reads the ~/.goobookrc and ~/.netrc.
    returns the configuration as a dictionary.

    '''
    config = Storage({ # Default values
        'email': '',
        'password': '',
        'max_results': '9999',
        'cache_filename': '~/.goobook_cache',
        'cache_expiry_hours': '24',
        })
    config_file = os.path.expanduser(config_file)
    if os.path.lexists(config_file) or os.path.lexists(config_file + '.gpg'):
        try:
            parser = ConfigParser.SafeConfigParser()
            if os.path.lexists(config_file):
                log.info('Reading config: %s', config_file)
                f = open(config_file)
            else:
                log.info('Reading config: %s', config_file + '.gpg')
                sp = subprocess.Popen(['gpg', '--no-tty', '-q', '-d', config_file + ".gpg"], stdout=subprocess.PIPE)
                f = sp.stdout
            parser.readfp(f)
            config.update(dict(parser.items('DEFAULT', raw=True)))
        except (IOError, ConfigParser.ParsingError), e:
            print >> sys.stderr, "Failed to read configuration %s\n%s" % (config_file, e)
            sys.exit(1)
开发者ID:discove12,项目名称:dotfiles,代码行数:28,代码来源:goobook.py


示例4: total_time_spent_by

	def total_time_spent_by(self, who, is_employee):
		who = 'E' + who if is_employee else 'G' + who

		s = Storage(self.name, self.token, True, True)
		if s.error:
			print(0)
			return

		s.verify_log()

		room_numbers, rooms, person_names, persons, current_timestamp = s.get_stats()

		if not who in person_names:
			print(0)
			return

		person = person_names[who]
		if person.is_employee != is_employee:
			libgeneric.print_error_and_exit("invalid")

		total_time = person.time_in_gallery

		if person.gallery_timestamp >= 0:
			total_time += (current_timestamp - person.gallery_timestamp)
		print(total_time)
开发者ID:rndCombo,项目名称:contestants_code_BIBIFI,代码行数:25,代码来源:log.py


示例5: rooms_entered_by

	def rooms_entered_by(self, who, is_employee):
		who = 'E' + who if is_employee else 'G' + who

		s = Storage(self.name, self.token, True)
		room_numbers, rooms, person_names, persons, _ = s.get_stats()
		log = s.get_log()
		print(','.join([str(e.room) for e in log if e.who == who and e.action == 'A' and e.room != -1 ]))
开发者ID:rndCombo,项目名称:contestants_code_BIBIFI,代码行数:7,代码来源:log.py


示例6: state

	def state(self):
		s = Storage(self.name, self.token, True)
		s.verify_log()
		room_numbers, rooms, person_names, persons, _ = s.get_stats()
		if persons:
			res = [p.name[1:] for p in persons if p.gallery_timestamp >= 0 and p.is_employee]
			res.sort()
			print(','.join(res))
			res = [p.name[1:] for p in persons if p.gallery_timestamp >= 0 and p.is_employee == False]
			res.sort()
			print(','.join(res))
		else:
			print()

		room_dir = {}

		for room in rooms:
			room_dir[room.number] = []

		for person in persons:
			if person.room >= 0:
				room_dir[rooms[person.room].number].append(person.name[1:])

		rooms_and_attendees = []
		for number, people in room_dir.items():
			people.sort()
			rooms_and_attendees.append( (number, ','.join(people)) )

		rooms_and_attendees.sort(key=lambda e : e[0])

		for rooms in rooms_and_attendees:
			if rooms[1] != '':
				print(str(rooms[0]) + ": " + rooms[1])
开发者ID:rndCombo,项目名称:contestants_code_BIBIFI,代码行数:33,代码来源:log.py


示例7: __init__

    def __init__(self, section, cfgfile="tor2web.conf"):
        Storage.__init__(self)

        self._cfgfile = cfgfile
        self._cfgparser = ConfigParser.ConfigParser()
        self._cfgparser.read([self._cfgfile])
        self._section = section
开发者ID:Syd,项目名称:Tor2web-3.0,代码行数:7,代码来源:config.py


示例8: wrapper

        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception, e:
                logging.error("Error: %s : %s", func.__name__, str(e))

                if not hasattr(e, 'errorCode'):
                    out.failureMessage("Sorry, operation has failed!!!.")
                    tools.exitErr()

                errorCode = int(e.errorCode)

                # auth-token error, re-auth
                if errorCode == 9:
                    storage = Storage()
                    storage.removeUser()
                    GeekNote()
                    return func(*args, **kwargs)

                elif errorCode == 3:
                    out.failureMessage("Sorry, you do not have permissions "
                                       "to do this operation.")

                # Rate limited
                # Patched because otherwise if you get rate limited you still keep
                # hammering the server on scripts
                elif errorCode == 19:
                    print("\nRate Limit Hit: Please wait %s seconds before continuing" %
                          str(e.rateLimitDuration))
                    tools.exitErr()

                else:
                    return False

                tools.exitErr()
开发者ID:khapota,项目名称:geeknote,代码行数:35,代码来源:geeknote.py


示例9: textToENML

    def textToENML(content, raise_ex=False, format='markdown'):
        """
        Create an ENML format of note.
        """
        if not isinstance(content, str):
            content = ""
        try:
            content = unicode(content, "utf-8")
            # add 2 space before new line in paragraph for creating br tags
            content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1  \n\3', content)
            if format=='markdown':
              storage = Storage()
              extras = storage.getUserprop('markdown2_extras')
              #contentHTML = markdown.markdown(content).encode("utf-8")
              contentHTML = markdown.markdown(
                      content, extras=extras).encode("utf-8")
              # Non-Pretty HTML output
              contentHTML = str(BeautifulSoup(contentHTML, 'html.parser'))
            else:
              contentHTML = Editor.HTMLEscape(content)
            return Editor.wrapENML(contentHTML)
        except:
            if raise_ex:
                raise Exception("Error while parsing text to html."
                                " Content must be an UTF-8 encode.")

            logging.error("Error while parsing text to html. "
                          "Content must be an UTF-8 encode.")
            out.failureMessage("Error while parsing text to html. "
                               "Content must be an UTF-8 encode.")
            return tools.exitErr()
开发者ID:elleryq,项目名称:geeknote,代码行数:31,代码来源:editor.py


示例10: parse_trees

def parse_trees(e, otus):
    "e is a nexml document parsed by etree"
    from ivy.tree import Node
    #from tree import Node
    v = []
    for tb in e.findall(NEXML+"trees"):
        for te in tb.findall(NEXML+"tree"):
            t = Storage()
            t.attrib = Storage(te.attrib)
            t.nodes = {}
            for n in te.findall(NEXML+"node"):
                node = Node()
                if n.attrib.get("otu"):
                    node.isleaf = True
                    node.otu = otus[n.attrib["otu"]]
                    node.label = node.otu.label
                t.nodes[n.attrib["id"]] = node
            for edge in te.findall(NEXML+"edge"):
                d = edge.attrib
                n = t.nodes[d["target"]]
                p = t.nodes[d["source"]]
                length = d.get("length")
                if length:
                    n.length = float(length)
                p.add_child(n)
            r = [ n for n in t.nodes.values() if not n.parent ]
            assert len(r)==1
            r = r[0]
            r.isroot = True
            for i, n in enumerate(r): n.id = i+1
            t.root = r
            v.append(t)
    return v
开发者ID:flfpesca,项目名称:phylografter,代码行数:33,代码来源:treebase.py


示例11: EvernoteController

class EvernoteController(object):
    def __init__(self, token, isSpecialToken = False, sandbox = False, isInternational = False, notebooks = None):
        self.token = token
        if sandbox:
            self.client = EvernoteClient(token=self.token)
        elif isInternational:
            self.client = EvernoteClient(token=self.token, service_host='www.evernote.com')
        else:
            self.client = EvernoteClient(token=self.token, service_host='app.yinxiang.com')
        self.isSpecialToken = isSpecialToken
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()
        self.storage = Storage(notebooks)
    def get_upload_limit(self):
        return {
            1: 25 * 1024 * 1024,
            3: 100 * 1024 * 1024,
            5: 200 * 1024 * 1024,
        }.get(self.userStore.getUser().privilege, 0)
    def create_notebook(self, noteFullPath):
        if self.get(noteFullPath): return False
        notebook = Types.Notebook()
        notebook.name = noteFullPath
        try:
            notebook = self.noteStore.createNotebook(notebook)
        except EDAMUserException, e:
            if e.errorCode == 10 and e.parameter == 'Notebook.name':
                self.storage.update(self.token, self.noteStore)
                return True
            else:
                raise e
        self.storage.create_notebook(notebook)
        return True
开发者ID:Yixf-Self,项目名称:LocalNote,代码行数:33,代码来源:controller.py


示例12: parse_chars

def parse_chars(e, otus):
    v = []
    for chars in e.findall(NEXML+"characters"):
        c = Storage(chars.attrib)
        c.states = parse_states(chars)
        c.meta = Storage()
        for meta in chars.findall(NEXML+"meta"):
            a = meta.attrib
            if a.get("content"):
                value = META_DATATYPE[a["datatype"]](a["content"])
                c.meta[a["property"]] = value
        c.matrices = []
        for matrix in chars.findall(NEXML+"matrix"):
            m = Storage()
            m.rows = []
            for row in matrix.findall(NEXML+"row"):
                r = Storage(row.attrib)
                r.otu = otus[r.otu]
                s = row.findall(NEXML+"seq")[0].text
                substrs = []
                for ss in AMBIG_RE.split(s):
                    if ss.startswith("{"):
                        key = frozenset(ss[1:-1])
                        val = c.states.states2symb.get(key)
                        if key and not val:
                            sys.stderr.write("missing ambig symbol for %s\n" %
                                             "".join(sorted(key)))
                        ss = val or "?"
                    substrs.append(ss)
                s = "".join(substrs)
                r.seq = s
                m.rows.append(r)
            c.matrices.append(m)
        v.append(c)
    return v
开发者ID:ChriZiegler,项目名称:ivy,代码行数:35,代码来源:treebase.py


示例13: wrapper

        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception, e:
                logging.error("Error: %s : %s", func.__name__, str(e))

                if not hasattr(e, 'errorCode'):
                    out.failureMessage("Sorry, operation has failed!!!.")
                    tools.exit()

                errorCode = int(e.errorCode)

                # auth-token error, re-auth
                if errorCode == 9:
                    storage = Storage()
                    storage.removeUser()
                    GeekNote()
                    return func(*args, **kwargs)

                elif errorCode == 3:
                    out.failureMessage("Sorry, you do not have permissions to do this operation.")

                else:
                    return False

                tools.exit()
开发者ID:jetgeng,项目名称:geeknote,代码行数:26,代码来源:geeknote.py


示例14: edit

    def edit(self):
        """
        Call the system editor, that types as a default in the system.
        Editing goes in markdown format, and then the markdown
        converts into HTML, before uploading to Evernote.
        """

        # Try to find default editor in the system.
        storage = Storage()
        editor = storage.getUserprop('editor')

        if not editor:
            editor = os.environ.get("editor")

        if not editor:
            editor = os.environ.get("EDITOR")

        if not editor:
            # If default editor is not finded, then use nano as a default.
            if sys.platform == 'win32':
                editor = config.DEF_WIN_EDITOR
            else:
                editor = config.DEF_UNIX_EDITOR

        # Make a system call to open file for editing.
        logging.debug("launch system editor: %s %s" % (editor, self.tempfile))

        out.preloader.stop()
        os.system(editor + " " + self.tempfile)
        out.preloader.launch()
        newContent = open(self.tempfile, 'r').read()

        return newContent
开发者ID:nloadholtes,项目名称:geeknote,代码行数:33,代码来源:editor.py


示例15: doit

def doit():

    set_logger(get_logfile_logger())

    my_remote_callbacks = MyRemoteCallbacks()

    set_remote_callbacks(my_remote_callbacks)

    environment = Environment(True, ProbeMode_STANDARD_WRITE_MOCKUP if save_mockup else ProbeMode_STANDARD, TargetMode_DIRECT)
    if save_mockup:
        environment.set_mockup_filename("mockup.xml")

    storage = Storage(environment)

    try:
        storage.probe()
    except Exception as exception:
        print(exception.what())
        exit(1)

    print()

    probed = storage.get_probed()

    print(probed)

    if save_devicegraph:
        probed.save("devicegraph.xml")
开发者ID:aschnell,项目名称:libstorage-ng,代码行数:28,代码来源:remote-probe.py


示例16: test_routes_absolute

 def test_routes_absolute(self):
     """
     Test absolute URL
     """
     load(data="")
     r = Storage()
     r.env = Storage()
     r.env.http_host = "domain.com"
     r.env.wsgi_url_scheme = "httpx"  # distinguish incoming scheme
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f")), "/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", host=True)), "httpx://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", host="host.com")), "httpx://host.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=True)), "httpx://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=False)), "/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme="https")), "https://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme="wss")), "wss://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=True, host=True)), "httpx://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme="https", host=True)), "https://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=False, host=True)), "httpx://domain.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=True, host="host.com")), "httpx://host.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=False, host="host.com")), "httpx://host.com/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", port=1234)), "httpx://domain.com:1234/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", scheme=True, port=1234)), "httpx://domain.com:1234/a/c/f")
     self.assertEqual(str(URL(r=r, a="a", c="c", f="f", host="host.com", port=1234)), "httpx://host.com:1234/a/c/f")
     self.assertEqual(
         str(URL(r=r, a="a", c="c", f="f", scheme="wss", host="host.com", port=1234)), "wss://host.com:1234/a/c/f"
     )
开发者ID:bsnipes,项目名称:TaskManager,代码行数:27,代码来源:test_routes.py


示例17: Updater

class Updater(object):

	days_befor_delete = 3

	def __init__(self):
		self.__logger = logging.getLogger(__name__)
		self.__load_config();
		self.__database = Database(self.__host,self.__db,self.__user,self.__password)
		self.__web = Web(self.__api_key, self.__url)
		self.__storage = Storage()
		self.last_update = self.__storage.get('last_update',date(1980,01,01))
		self.last_delete = self.__storage.get('last_delete',date.today())
		self.days = timedelta(days = self.days_befor_delete)
		self.to_delete = date.today() - self.days

	def __delete(self):
		self.__logger.info('Removing old data from the database...')
		data = self.__database.get_delete_data(str(self.last_delete), str(self.to_delete))
		self.__web.delete_geodata(data)
		self.__logger.info('finished')
		self.__storage['last_delete'] = self.to_delete


	def __add(self):
		self.__logger.info('Adding new data to the database...')
		if (self.last_update > self.to_delete):
			data = self.__database.get_new_data(self.last_update)
		else:
			data = self.__database.get_data(self.last_update, self.to_delete)
		self.__web.add_geodata(data)
		self.__logger.info('finished')
		self.__storage['last_update'] = date.today()

	def __close(self):
		self.__logger.debug("Updateing stored dates. last_update: " + str(date.today()) + ", last_delete: " + str(self.to_delete))
		self.__storage.close()

	def run(self):
		self.__logger.info('Starting updater...')
		self.__logger.debug('Last update: ' + str(self.last_update) + ' with delete date: ' + str(self.last_delete) + '. Delete data which is ' + str(self.days_befor_delete) + ' old.')
		if (self.last_update < date.today()):
			self.__add()
			self.__delete()
		else:
			self.__logger.info('Not run. Data is uptodate.')
		self.__close()
		self.__logger.info('Finish updater')

	def __load_config(self):
		config = RawConfigParser()
		config.readfp(open('config.cfg'))
		# Database config
		self.__host = config.get('Database','host')
		self.__db = config.get('Database','database')
		self.__user = config.get('Database','user')
		self.__password = config.get('Database','password')
		# Web config
		self.__api_key = config.get('web','api_key')
		self.__url = config.get('web','url')
开发者ID:initdch,项目名称:datamanager-cli,代码行数:59,代码来源:updater.py


示例18: buildform

def buildform(_table_name, *field):
    form = Storage()
    form._tablename = _table_name
    for f in field:
        f._tablename = _table_name
        form[f.name] = f
    form.fields = [f.name for f in field]
    return form
开发者ID:wangking,项目名称:formbuilder,代码行数:8,代码来源:tablebuilder.py


示例19: test_getlast

 def test_getlast(self):
     # usually with request.vars
     a = Storage()
     a.x = 'abc'
     a.y = ['abc', 'def']
     self.assertEqual(a.getlast('x'), 'abc')
     self.assertEqual(a.getlast('y'), 'def')
     self.assertEqual(a.getlast('z'), None)
开发者ID:Crusnik-san,项目名称:web2py,代码行数:8,代码来源:test_storage.py


示例20: append

	def append(self, timestamp, action, person, is_employee, room=-1):
		if room == None:
			room = -1
		else:
			room = int(room)

		s = Storage(self.name, self.token, readonly=False)
		s.append(person, is_employee, action, int(timestamp), room)
开发者ID:rndCombo,项目名称:contestants_code_BIBIFI,代码行数:8,代码来源:log.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python misc.execCmd函数代码示例发布时间:2022-05-27
下一篇:
Python storage.load函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap