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


Python PersistentMapping.iteritems方法代码示例

本文整理汇总了Python中persistent.mapping.PersistentMapping.iteritems方法的典型用法代码示例。如果您正苦于以下问题:Python PersistentMapping.iteritems方法的具体用法?Python PersistentMapping.iteritems怎么用?Python PersistentMapping.iteritems使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在persistent.mapping.PersistentMapping的用法示例。


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

示例1: checkBasicOps

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import iteritems [as 别名]
    def checkBasicOps(self):
        from persistent.mapping import PersistentMapping
        m = PersistentMapping({'x': 1}, a=2, b=3)
        m['name'] = 'bob'
        self.assertEqual(m['name'], "bob")
        self.assertEqual(m.get('name', 42), "bob")
        self.assert_('name' in m)

        try:
            m['fred']
        except KeyError:
            pass
        else:
            self.fail("expected KeyError")
        self.assert_('fred' not in m)
        self.assertEqual(m.get('fred'), None)
        self.assertEqual(m.get('fred', 42), 42)

        keys = m.keys()
        keys.sort()
        self.assertEqual(keys, ['a', 'b', 'name', 'x'])

        values = m.values()
        values.sort()
        self.assertEqual(values, [1, 2, 3, 'bob'])

        items = m.items()
        items.sort()
        self.assertEqual(items,
                         [('a', 2), ('b', 3), ('name', 'bob'), ('x', 1)])

        keys = list(m.iterkeys())
        keys.sort()
        self.assertEqual(keys, ['a', 'b', 'name', 'x'])

        values = list(m.itervalues())
        values.sort()
        self.assertEqual(values, [1, 2, 3, 'bob'])

        items = list(m.iteritems())
        items.sort()
        self.assertEqual(items,
                         [('a', 2), ('b', 3), ('name', 'bob'), ('x', 1)])
开发者ID:Andyvs,项目名称:TrackMonthlyExpenses,代码行数:45,代码来源:testPersistentMapping.py

示例2: checkBasicOps

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import iteritems [as 别名]
    def checkBasicOps(self):
        from persistent.mapping import PersistentMapping

        m = PersistentMapping({"x": 1}, a=2, b=3)
        m["name"] = "bob"
        self.assertEqual(m["name"], "bob")
        self.assertEqual(m.get("name", 42), "bob")
        self.assert_("name" in m)

        try:
            m["fred"]
        except KeyError:
            pass
        else:
            self.fail("expected KeyError")
        self.assert_("fred" not in m)
        self.assertEqual(m.get("fred"), None)
        self.assertEqual(m.get("fred", 42), 42)

        keys = m.keys()
        keys.sort()
        self.assertEqual(keys, ["a", "b", "name", "x"])

        values = m.values()
        values.sort()
        self.assertEqual(values, [1, 2, 3, "bob"])

        items = m.items()
        items.sort()
        self.assertEqual(items, [("a", 2), ("b", 3), ("name", "bob"), ("x", 1)])

        keys = list(m.iterkeys())
        keys.sort()
        self.assertEqual(keys, ["a", "b", "name", "x"])

        values = list(m.itervalues())
        values.sort()
        self.assertEqual(values, [1, 2, 3, "bob"])

        items = list(m.iteritems())
        items.sort()
        self.assertEqual(items, [("a", 2), ("b", 3), ("name", "bob"), ("x", 1)])
开发者ID:grodniewicz,项目名称:oship,代码行数:44,代码来源:testPersistentMapping.py

示例3: PatchedDirectory

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import iteritems [as 别名]
class PatchedDirectory (FileMeta):

    ftype = fs.DIRECTORY

    EXISTING = 0
    ADDED    = 1
    REMOVED  = 2
    
    def __init__(self, name, parent, uid, gid, mode, mtime_ns):
        FileMeta.__init__(self, name, parent, uid, gid, mode, mtime_ns)
        
        self.adds         = PersistentMapping()
        self.removes      = PersistentMapping()
        self.meta_changes = PersistentMapping() # name => ((to_uid, to_gid, to_mode), (from_uid, from_gid, from_mode))

        self.subdirs      = PersistentMapping()

        self.state        = PatchedDirectory.EXISTING

    def pdbg(self, indent = ''):
        s = { 0 : 'EXISTING', 1 : 'ADDED', 2 : 'REMOVED' }
        
        print indent, 'Dir %s %s' % (s[self.state], self.dbg_meta())
        
        if self.adds:
            print indent, ' ** Adds **'
            for v in self.adds.itervalues():
                v.pdbg( indent + '   ' )
        if self.removes:
            print indent, ' ** Removes **'
            for v in self.removes.itervalues():
                v.pdbg( indent + '   ' )

        if self.meta_changes:
            print indent, ' ** Meta Mods **'
            for k, v in self.removes.iteritems():
                print indent + '   ', k, v

        for s in self.subdirs.itervalues():
            s.pdbg( indent + '   ' )
开发者ID:cocagne,项目名称:scratch,代码行数:42,代码来源:types.py

示例4: Book

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import iteritems [as 别名]
class Book( Persistent ):
    ''' This is a user book to include user's orders, one per user '''
    def __init__(self, user=None):
        self.user = user
        self.orders = PersistentList()
        self.positions = PersistentMapping()

    def addOrder(self, order):
        if order.instrument in self.positions:
            self.positions[order.instrument].append(order)
        else:
            self.positions[order.instrument] = PersistentList(order)

    def cost(self):
        cost=0.0
        for orders in self.positions.itervalues():
            cost += sum([o.cost() for o in orders])
        return

    def marketValue(self):
        mktval = 0.0
        for inst, orders in self.positions.iteritems():
            mktval += inst.marketPrice * sum([o.amountMatched for o in orders])
        return mktval
开发者ID:charlesbo,项目名称:cintra,代码行数:26,代码来源:books.py

示例5: PasswordResetTool

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import iteritems [as 别名]

#.........这里部分代码省略.........
                        user_info['email']
                    _set_session_message(REQUEST, 'error', msg)
                    location = (
                        self.absolute_url() +
                        '/messages_html?msg=email-disabled')
                else:
                    token = self._new_token(user_info['id'])
                    log.info(
                        "Sending password recovery email to user %r at %r.",
                        user_info['id'], email)
                    self._send_token_email(email, token, user_info)

                    location = (self.absolute_url() +
                                '/messages_html?msg=email-sent')

        else:
            log.info("Requested password recovery with invalid email %r.",
                     email)
            msg = "Email address not found in database."
            _set_session_message(REQUEST, 'error', msg)
            location = self.absolute_url() + '/'

        if REQUEST:
            REQUEST.RESPONSE.redirect(location)

    security.declareProtected(view, 'messages_html')

    def messages_html(self, REQUEST):
        """ view """
        options = {
            'message-name': REQUEST.form['msg'],
        }
        return self._render_template('zpt/pwreset_message.zpt', **options)

    def _say_token_expired(self, REQUEST):
        msg = ("Password reset link is invalid, perhaps it has "
               "expired. Please try again.")
        _set_session_message(REQUEST, 'error', msg)
        location = self.absolute_url() + '/'
        REQUEST.RESPONSE.redirect(location)

    def _expire_tokens(self):
        expired = []
        cutoff_time = datetime.utcnow() - timedelta(days=1)
        for token, token_data in self._tokens.iteritems():
            if token_data.timestamp < cutoff_time:
                expired.append(token)
        for token in expired:
            log.info('Token %r expired.', token)
            del self._tokens[token]

    security.declareProtected(view, 'confirm_email')

    def confirm_email(self, REQUEST):
        """ view """

        token = REQUEST.form['token']
        self._expire_tokens()
        token_data = self._tokens.get(token, None)

        if token_data is None:
            return self._say_token_expired(REQUEST)

        options = {
            'token': token,
            'user_id': token_data.user_id,
        }
        return self._render_template('zpt/pwreset_new_password.zpt', **options)

    def reset_password(self, REQUEST):
        """ view """

        token = REQUEST.form['token']
        self._expire_tokens()
        token_data = self._tokens.get(token, None)

        if token_data is None:
            return self._say_token_expired(REQUEST)

        new_password = REQUEST.form['password']
        if new_password != REQUEST.form['password-confirm']:
            _set_session_message(REQUEST, 'error', "Passwords do not match.")
            location = self.absolute_url() + '/confirm_email?token=' + token

        else:
            log.info("Restting password for user %r with token %r",
                     token_data.user_id, token)
            agent = self._get_ldap_agent(bind=True)
            agent.set_user_password(token_data.user_id, None, new_password)
            del self._tokens[token]
            location = (self.absolute_url() +
                        '/messages_html?msg=password-reset')

        REQUEST.RESPONSE.redirect(location)

    security.declareProtected(view, 'can_edit_users')

    def can_edit_users(self):
        user = self.REQUEST.AUTHENTICATED_USER
        return bool(user.has_permission(eionet_edit_users, self))
开发者ID:,项目名称:,代码行数:104,代码来源:

示例6: Analysis

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import iteritems [as 别名]

#.........这里部分代码省略.........
        if classname(cls) not in self._entities:
            # self.entities contains a tuple 1. with all emlements and 2. with an BTree over the primary identifier
            self._entities[classname(cls)] = (PersistentList(), OOBTree.BTree())

        entity = self._entities[classname(cls)]

        res = cls.find(context, entity[0], entity[1], *args)

        if res is None:
            res = cls(context, *args)
            assert isinstance(res, Entity)
            entity[0].append(res)

            if res.primary_identifier not in entity[1]:
                entity[1][res.primary_identifier] = PersistentList()

            entity[1][res.primary_identifier].append(res)

        return res

    def iter_all_events(self, context, key=None, min_value=None, max_value=None, value=None):
        """Iterates over all event classes.

        Args:
            context (ambrosia_web.context.AmbrosiaContext): the current context
            key: the key we are searching for
            min_value: the minimum value
            max_value: the maximum value
            value: the specific value (to search for exactly one value)

        This method works just like :func:`Analysis.iter_events` but is not limited to a certain entity Type. Instead,
        it searches entitiy of all types.
        """
        for class_name, idx in self._event_index.iteritems():
            cls = get_class(class_name)
            assert issubclass(cls, Event)

            if key not in cls.indices:
                continue

            for evt in self.iter_events(context, cls, key, min_value, max_value, value):
                yield evt

    def iter_events(self, context, cls=None, key=None, min_value=None, max_value=None, value=None):
        """Iterates over all events matching specific conditions in an efficient manner.

        Args:
            context (ambrosia_web.context.AmbrosiaContext): the current context
            cls (class): the class of the events we are looking for
            key: the key we are searching for
            min_value: the minimum value
            max_value: the maximum value
            value: the specific value (to search for exactly one value)

        This method uses a internal indices to efficiently select specific events. Each event class defines attributes
        that should be indexed (:class:`Event`.indices). This class makes sure that those attributes can be searched for
        very fast.

        The method accepts the following combinations of argument:
        * nothing: return all events
        * *cls*: return all events of a specific class (inefficient)
        * *cls*, *key*, *min_value* and/or *max_value*: search for all events of a specific class where the attribute
        *key* is within the defined value constraints
        * *cls*, *key*, *value*: search all events of a specific class where the attribute *key* has the value *value*
        """
        assert isinstance(context, ambrosia.context.AmbrosiaContext)
开发者ID:MalwareLabHagenberg,项目名称:ambrosia,代码行数:70,代码来源:__init__.py


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