本文整理汇总了Python中persistent.mapping.PersistentMapping.items方法的典型用法代码示例。如果您正苦于以下问题:Python PersistentMapping.items方法的具体用法?Python PersistentMapping.items怎么用?Python PersistentMapping.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类persistent.mapping.PersistentMapping
的用法示例。
在下文中一共展示了PersistentMapping.items方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: persist
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
def persist(data):
if isinstance(data, dict):
data = PersistentMapping(data)
for key, value in data.items():
data[key] = persist(value)
elif isinstance(data, list):
return PersistentList(map(persist, data))
else:
# Usually we got basestrings, or integer here, so do nothing.
pass
return data
示例2: checkBasicOps
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [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)])
示例3: make_persistent
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
def make_persistent(data):
if isinstance(data, dict) or \
isinstance(data, PersistentMapping):
data = PersistentMapping(data)
for key, value in data.items():
value = make_persistent(value)
data[key] = value
elif isinstance(data, list) or \
isinstance(data, PersistentList):
new_data = PersistentList()
for item in data:
new_data.append(make_persistent(item))
data = new_data
return data
示例4: checkBasicOps
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [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)])
示例5: NotificationTool
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
#.........这里部分代码省略.........
return 0
if self.ignoreNotification(discussion_item):
return 0
## We add two bindings to disambiguate the meaning of 'here'
## in the mail template and the rules: 'discussion_item' and
## 'discussed_item'.
discussed_item = discussion_item
while discussed_item.meta_type == discussion_item.meta_type:
discussed_item = discussed_item.aq_inner.aq_parent.aq_parent
extra_bindings = getBasicBindings(discussed_item)
extra_bindings.update({'discussion_item': discussion_item,
'discussed_item': discussed_item})
return self._handlerHelper(discussion_item,
'discussion_item_creation',
extra_bindings,
extra_bindings,
extra_bindings)
def _handlerHelper(self, obj, what,
get_users_extra_bindings,
mail_template_extra_bindings,
mail_template_options):
"""An helper method for ``on*()`` handlers.
It returns the number of mails which have been sent.
"""
self._updateSubscriptionMapping(obj)
users_by_label = self.getUsersToNotify(obj, what,
get_users_extra_bindings)
if self.isExtraSubscriptionsEnabled():
users = users_by_label.get('', [])
users.extend(self.getExtraSubscribersOf(self._getPath(obj)).items())
users_by_label[''] = users
n_sent = 0
for label, users in users_by_label.items():
users = self.removeUnAuthorizedSubscribers(users, obj)
mail_template_extra_bindings['label'] = label
for user, how in users:
# Fetch the delivery utilities the user requested, then use
# that to notify
for h in how:
try:
delivery = getUtility(INotificationDelivery, h)
except:
# The method is not known, or the third party
# product that provided it was uninstalled
LOG.warning("Could not look up INotificationDelivery "\
"utility named '%s'", h)
continue
n_sent += delivery.notify(obj, user, what, label,
get_users_extra_bindings, mail_template_extra_bindings,
mail_template_options)
return n_sent
#################################################################
#################################################################
## Utility methods
###############################
decPrivate('ignoreNotification')
def ignoreNotification(self, obj):
"""Return whether notification have been set to be ignored for
示例6: DecaObject
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
class DecaObject(Persistent):
"""A generic DECA object"""
def __init__(self, id=None):
Persistent.__init__(self)
if id is not None:
self.ID = id
else:
self.ID = uuid.uuid4()
self.TemplateName = ""
self.Attributes = PersistentMapping()
self.TitleAttr = None
self.Graphics = None
self.IsReflection = False
self.Tag = None
def copy(self, newID):
obj = DecaObject(newID)
obj.TemplateName = self.TemplateName
obj.TitleAttr = self.TitleAttr
for k, v in self.Attributes.items():
obj.Attributes[k] = v
obj.Graphics = self.Graphics
obj.IsReflection = self.IsReflection
obj.Tag = self.Tag
return obj
def GetTitle(self):
"""Returns the title of the object. If the Title Attribute defined, it's value will be returned.
Else if Tag defined, it's value will be returned. Else the object's ID will be returned. """
if self.TitleAttr is not None:
return self.Attributes[self.TitleAttr]
if self.Tag is not None and str(self.Tag) != "":
return str(self.Tag)
return str(self.ID)
def SetAttr(self, name, value, location=LOCAL):
"""Sets the attribute value in desired location.
**Note:** if the object isn't the reflect, attribute will be stored locally"""
if location == LOCAL:
self.Attributes[name] = value
# todo: set attribute to the base object if we are reflection
def GetAttr(self, name, default=None, priority=LOCAL):
"""Gets the attribute value. For the reflects the priority may points that the base value must be given.
If value absent in desired location other locations will be scanned. Finnaly, the default value will be returned"""
result = default
if priority == LOCAL:
result = self.Attributes.get(name, default)
else:
# todo: read base object's property if we are reflection
pass
return result
def GetShape(self):
# todo: get shape description. Is it necessary?
return
def GetPropList(self, holder=None):
self.propsGrid = holder
props = OrderedDict(
[
("Identity", self.ID),
("Template", self.TemplateName),
("Title Attribute", self.TitleAttr),
("Is Reflection", self.IsReflection),
]
)
attrs = OrderedDict([])
for k, v in self.Attributes.items():
attrs.update([(k, v)])
result = OrderedDict([(_("Object's properties"), props), (_("Local object's attributes"), attrs)])
return result
def ReflectTo(self, dstLayer):
if not isinstance(dstLayer, Deca.Layer):
dstLayer = Deca.world.GetLayer(str(dstLayer))
if not self.ID in dstLayer.storage.objects.keys():
nwo = self.copy(self.ID)
nwo.IsReflection = True
dstLayer.AddObject(nwo)
return nwo
return None
def GetEngines(self):
def genList(base, dirlist):
res = []
for ent in dirlist:
if os.path.isdir(os.path.join(base, ent)):
# process subdir
nb = os.path.join(base, ent)
res.append((ent, genList(nb, os.listdir(nb))))
else:
ft = os.path.splitext(ent)
if ft[1].lower() == ".py" and not ft[0].startswith("_"):
res.append(ft[0])
return res
# main function
#.........这里部分代码省略.........
示例7: address
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
class HasEmail:
"""Mixin class proving email address(es) and related functions"""
def __init__(self):
self.__items = []
self.__unconfirmed = PersistentMapping()
self.primary_email = None
def is_valid_email(cls, email):
"""Class method returns True if email is valid, or False if it should
be rejected.
>>> HasEmail.is_valid_email('[email protected]')
True
>>> HasEmail.is_valid_email('[email protected]')
True
>>> HasEmail.is_valid_email('[email protected]')
True
>>> HasEmail.is_valid_email('xyz')
False
>>> HasEmail.is_valid_email('[email protected]@foo')
False
"""
global _blocked_domains
if email.find('@') == -1:
return False
if email.count('@') != 1:
return False
(username, host) = email.split('@')
if host in _blocked_domains:
return False
return True
is_valid_email = classmethod(is_valid_email)
def add_email(self, email):
"""Add email to the list. Adds primary if none set."""
email = email.lower()
if email not in self.__items:
self.__items.append(email)
self._p_changed = 1
if self.primary_email is None:
self.primary_email = email
def add_unconfirmed_email(self, email):
"""Add new e-mail that has not yet been confirmed. Call confirm_email to move
into active list of e-mails.
Returns confirmation code that must be given to confirm_email to confirm.
"""
email = email.lower()
if not self.__unconfirmed.has_key(email):
self.__unconfirmed[email] = _password_generator.generate(seed=email)
return self.__unconfirmed[email]
def remove_unconfirmed_email(self, email):
email = email.lower()
if self.__unconfirmed.has_key(email):
del self.__unconfirmed[email]
def confirm_email(self, code):
"""Confirm email with the given code, or return False if invalid code."""
for email, conf_code in self.__unconfirmed.items():
if conf_code == code:
self.add_email(email)
del self.__unconfirmed[email]
self.notify_email_confirmed(email)
return email
return None
def remove_email(self, email):
"""Remove an e-mail address from the list. Raises KeyError if only one e-mail address left"""
email = email.lower()
if self.__unconfirmed.has_key(email):
return self.remove_unconfirmed_email(email)
emails = self.email_list()
if len(emails) > 1:
self.__items.remove(email)
self._p_changed = 1
if email == self.get_primary_email():
self.set_primary_email(self.email_list()[0])
else:
raise KeyError
def remove_all_emails(self):
self.__items = []
self.primary_email = None
def has_email(self, email):
email = email.lower()
return email in self.__items
def email_list(self):
return self.__items
#.........这里部分代码省略.........
示例8: BaseQuestion
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
class BaseQuestion(BaseContent):
"""Base class for survey questions"""
immediate_view = "base_edit"
global_allow = 0
filter_content_types = 1
allowed_content_types = ()
include_default_actions = 1
_at_rename_after_creation = True
def __init__(self, oid, **kwargs):
self.reset()
BaseContent.__init__(self, oid, **kwargs)
security = ClassSecurityInfo()
security.declareProtected(CMFCorePermissions.View, 'getAbstract')
def getAbstract(self, **kw):
return self.Description()
security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'setAbstract')
def setAbstract(self, val, **kw):
self.setDescription(val)
security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'reset')
def reset(self):
"""Remove answers for all users."""
if USE_BTREE:
self.answers = OOBTree()
else:
self.answers = PersistentMapping()
security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'resetForUser')
def resetForUser(self, userid):
"""Remove answer for a single user"""
if self.answers.has_key(userid):
del self.answers[userid]
security.declareProtected(CMFCorePermissions.View, 'addAnswer')
def addAnswer(self, value, comments=""):
"""Add an answer and optional comments for a user.
This method protects _addAnswer from anonymous users specifying a
userid when they vote, and thus apparently voting as another user
of their choice.
"""
# Get hold of the parent survey
survey = None
ob = self
while survey is None:
ob = ob.aq_parent
if ob.meta_type == 'Survey':
survey = ob
elif getattr(ob, '_isPortalRoot', False):
raise Exception("Could not find a parent Survey.")
portal_membership = getToolByName(self, 'portal_membership')
if portal_membership.isAnonymousUser() and not survey.getAllowAnonymous():
raise Unauthorized, ("This survey is not available to anonymous users.")
# Use the survey to get hold of the appropriate userid
userid = survey.getSurveyId()
# Call the real method for storing the answer for this user.
return self._addAnswer(userid, value, comments)
def _addAnswer(self, userid, value, comments=""):
"""Add an answer and optional comments for a user."""
# We don't let users over-write answers that they've already made.
# Their first answer must be explicitly 'reset' before another
# answer can be supplied.
# XXX this causes problem when survey fails validation
# will also cause problem with save function
## if self.answers.has_key(userid):
## # XXX Should this get raised? If so, a more appropriate
## # exception is probably in order.
## msg = "User '%s' has already answered this question. Reset the original response to supply a new answer."
## raise Exception(msg % userid)
## else:
self.answers[userid] = PersistentMapping(value=value,
comments=comments)
if not isinstance(self.answers, (PersistentMapping, OOBTree)):
# It must be a standard dictionary from an old install, so
# we need to inform the ZODB about the change manually.
self.answers._p_changed = 1
security.declareProtected(CMFCorePermissions.View, 'getAnswerFor')
def getAnswerFor(self, userid):
"""Get a specific user's answer"""
answer = self.answers.get(userid, {}).get('value', None)
if self.getInputType() in ['multipleSelect', 'checkbox']:
if type(answer) == 'NoneType':
return []
return answer
security.declareProtected(CMFCorePermissions.View, 'getCommentsFor')
def getCommentsFor(self, userid):
"""Get a specific user's comments"""
return self.answers.get(userid, {}).get('comments', None)
security.declareProtected(CMFCorePermissions.View, 'getComments')
def getComments(self):
"""Return a userid, comments mapping"""
mlist = []
for k, v in self.answers.items():
#.........这里部分代码省略.........
示例9: NotificationTool
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
#.........这里部分代码省略.........
"""Return ``True`` iff extra subscriptions are recursive.
Note that this method does not check whether extra
subscriptions are enabled or not.
"""
return self.getProperty('extra_subscriptions_recursive')
decProtected('View', 'isExtraSubscriptionsForAuthenticatedOnly')
def isExtraSubscriptionsForAuthenticatedOnly(self):
"""Return ``True iff extra subscriptions are restricted to
authenticated users.
Note that this method does not check whether extra
subscriptions are enabled or not.
"""
return self.getProperty('extra_subscriptions_for_authenticated_only')
#################################################################
#################################################################
## Extra subscriptions logic
############################
def _updateSubscriptionMapping(self, obj):
"""Update subscription mapping."""
uid = self._getUID(obj)
if uid is not None:
path = self._getPath(obj)
known_path = self._uid_to_path.get(uid)
if known_path != path:
self._uid_to_path[uid] = path
if known_path is not None:
## We have old informations for this object
for key, value in self._subscriptions.items():
if key.startswith(known_path):
new_key = path + key[len(known_path) : ]
self._subscriptions[new_key] = value
del self._subscriptions[key]
decPublic('currentUserHasSubscribePermission')
def currentUserHasSubscribePermissionOn(self, obj):
"""Return ``True`` iff the current user has ``SUBSCRIBE_PERMISSION``
on ``obj``.
"""
mtool = getToolByName(self, 'portal_membership')
return mtool.checkPermission(SUBSCRIBE_PERMISSION, obj)
decPublic('subscriptionToParentIsAllowed')
def isSubscriptionToParentAllowed(self, obj):
"""Return ``True`` iff subscription to the parent of ``obj`` (i.e. the
first folderish item above ``obj``) is allowed.
This method uses Plone specific scripts.
"""
if self.isExtraSubscriptionsRecursive() \
and not obj.is_folderish() \
and obj.isDefaultPageInFolder():
try:
parent = obj.aq_parent
except ConflictError:
raise
except:
return False
return self.currentUserHasSubscribePermissionOn(parent)
示例10: Box
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import items [as 别名]
class Box(Persistent):
implements(IDepositBox)
def __init__(self, max_age=config.MAX_AGE, purge_days=config.PURGE_DAYS):
self.data = PersistentMapping()
self._last_purge = int(time.time())
self.max_age = max_age
self.purge_days = purge_days
def _generate_new_id(self):
"""Generate new id.
"""
new_id = id_generator()
while new_id in self.data.keys():
new_id = id_generator()
return new_id
def put(self, value, token=None):
"""Put value in box, with optional token, and return generated id.
Calling this method also does a purge once a day (well, when
the last purge was at least 24 hours ago). The frequency can
be controlled with the purge_days attribute.
"""
cutoff = int(time.time()) - (self.purge_days * 86400)
if self._last_purge < cutoff:
self.purge()
if value is None:
raise ValueError
id = self._generate_new_id()
self.data[id] = BoxItem(token, value, confirmed=False)
return id
def edit(self, secret, value, token=None):
"""Edit value in the box, when secret and optional token match.
"""
if value is None:
raise ValueError
stored = self.get(secret, token=token)
if value == stored:
# No change
return
self.data[secret] = BoxItem(token, value, confirmed=True)
def get(self, secret, token=None):
stored = self.data.get(secret)
if stored is None:
return None
if stored.token != token:
# raise Exception
return None
if not stored.confirmed:
# Purge this item when it is expired:
cutoff = int(time.time()) - self.max_age * 86400
if stored.timestamp < cutoff:
del self.data[secret]
return None
if token:
# When there is a token, the item must be confirmed
# before we return the value. Main use case: email
# confirmation.
return None
return stored.value
def confirm(self, secret, token=None):
"""Confirm the item/token and return whether this succeeded or not.
"""
stored = self.data.get(secret)
if stored is None:
return None
if stored.token != token:
# raise Exception?
return None
if not stored.confirmed:
# First check if the confirmation comes too late.
cutoff = int(time.time()) - self.max_age * 86400
if stored.timestamp < cutoff:
del self.data[secret]
# Report back that we have failed, in case anyone
# wants to know.
return False
stored.confirmed = True
return True
def pop(self, secret, token=None):
stored = self.get(secret, token=token)
if stored is None:
return None
self.data.pop(secret)
return stored
def get_all_confirmed(self):
for key, stored in self.data.items():
if stored.confirmed:
yield stored.value
def purge(self):
"""Purge items that have expired.
#.........这里部分代码省略.........