本文整理汇总了Python中persistent.mapping.PersistentMapping.keys方法的典型用法代码示例。如果您正苦于以下问题:Python PersistentMapping.keys方法的具体用法?Python PersistentMapping.keys怎么用?Python PersistentMapping.keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类persistent.mapping.PersistentMapping
的用法示例。
在下文中一共展示了PersistentMapping.keys方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_persistent_mapping
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
def test_persistent_mapping(self):
value = PersistentMapping({'foo': 'bar'})
self.assertEquals({u'foo': u'bar'}, json_compatible(value))
self.assertEquals('{"foo": "bar"}', json.dumps(json_compatible(value)))
self.assertIsInstance(json_compatible(value.keys()[0]),
unicode,
'Dict keys should be converted recursively.')
self.assertIsInstance(json_compatible(value.values()[0]),
unicode,
'Dict values should be converted recursively.')
示例2: upgrade_carousel_tiles_custom_url
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
def upgrade_carousel_tiles_custom_url(context):
# Get covers
covers = context.portal_catalog(portal_type='collective.cover.content')
logger.info('About to update %s covers' % len(covers))
for cover in covers:
obj = cover.getObject()
tile_ids = obj.list_tiles(types=[
u'collective.cover.carousel',
u'collective.cover.list'
])
for tile_id in tile_ids:
tile = obj.get_tile(tile_id)
old_data = ITileDataManager(tile).get()
uuids = old_data['uuids']
if isinstance(uuids, PersistentMapping):
# This tile is fixed, carry on
logger.info(
'Tile %s at %s was already updated' %
(tile_id, cover.getPath())
)
continue
if not uuids:
# This tile did not have data, so ignore
logger.info(
'Tile %s at %s did not have any data' %
(tile_id, cover.getPath())
)
continue
new_data = PersistentMapping()
order = 0
for uuid in uuids:
if uuid not in new_data.keys():
entry = PersistentMapping()
entry[u'order'] = unicode(order)
new_data[uuid] = entry
order += 1
old_data['uuids'] = new_data
ITileDataManager(tile).set(old_data)
logger.info(
'Tile %s at %s updated' % (tile_id, cover.getPath())
)
logger.info('Done')
示例3: checkBasicOps
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [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)])
示例4: checkBasicOps
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [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: PeopleDirectory
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
class PeopleDirectory(Folder):
implements(IPeopleDirectory)
title = 'People'
def __init__(self):
super(PeopleDirectory, self).__init__()
self.categories = PersistentMapping() # {id: PeopleCategory}
self.categories.__parent__ = self
self.catalog = CachingCatalog()
self.catalog.document_map = DocumentMap()
self.update_indexes()
self.order = () # order of sections
# Set up a default configuration
self['all'] = section = PeopleSection('All')
section['all'] = report = PeopleReport('All')
report.set_columns(['name', 'organization', 'location', 'email'])
self.set_order(['all'])
def set_order(self, order):
self.order = tuple(order)
def update_indexes(self):
indexes = {
'lastfirst': CatalogFieldIndex(get_lastfirst),
'lastnamestartswith': CatalogFieldIndex(get_lastname_firstletter),
'texts': CatalogTextIndex(get_textrepr),
# path index is needed for profile deletion
'path': CatalogPathIndex2(get_path, attr_discriminator=get_acl),
'allowed': CatalogKeywordIndex(get_allowed_to_view),
'is_staff': CatalogFieldIndex(is_staff),
'groups': CatalogKeywordIndex(get_groups),
# provide indexes for sorting reports
'department': CatalogFieldIndex(get_department),
'email': CatalogFieldIndex(get_email),
'location': CatalogFieldIndex(get_location),
'organization': CatalogFieldIndex(get_organization),
'phone': CatalogFieldIndex(get_phone),
'position': CatalogFieldIndex(get_position),
}
# provide indexes for filtering reports
for catid in self.categories.keys():
getter = ProfileCategoryGetter(catid)
indexes['category_%s' % catid] = CatalogKeywordIndex(getter)
catalog = self.catalog
need_reindex = False
# add indexes
for name, index in indexes.items():
if name not in catalog:
catalog[name] = index
need_reindex = True
# remove indexes
for name in catalog.keys():
if name not in indexes:
del catalog[name]
return need_reindex
示例6: BibliographyTool
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
#.........这里部分代码省略.........
this is only half of the truth!!! (ITranslatable)
"""
return self.bibrefitems_translatable
security.declarePublic('getMemberTypes')
def getMemberTypes(self, default=()):
member_types = self.getProperty('member_types', default)
if not isinstance(member_types, (list, tuple)):
return (member_types,)
else:
return member_types
security.declarePublic('getSortMembersOn')
def getSortMembersOn(self, default='getId'):
return self.getProperty('sort_members_on', default)
security.declarePublic('getSelectMembersAttr')
def getSelectMembersAttr(self, default='Title'):
return self.getProperty('select_members_attr', default)
security.declarePublic('getMembersSearchOnAttr')
def getMembersSearchOnAttr(self, default='Title'):
return self.getProperty('members_search_on_attr', default)
security.declarePublic('getReferenceTypes')
def getReferenceTypes(self, display=False):
"""
returns a list with the names (meta types) of the
currently registered reference types of a BibliographyFolder
"""
if display:
return DisplayList(tuple([ (key, key) for key in self.getReferenceTypes() ]))
else:
return self._reference_types.keys()
security.declarePublic('getBibFolderTypes')
def getBibFolderTypes(self):
"""
returns a list with the names (meta types) of the
currently registered bibfolder types
"""
return BIBFOLDER_TYPES
security.declareProtected(permissions.ManageReferenceTypes,
'registerReferenceType')
def registerReferenceType(self, portal_type):
"""Add portal_type to the list that should be considered references
for this plone instance. Do not fail on duplicates.
"""
# self._reference_types is a PersistentMapping
self._reference_types[portal_type] = None
security.declareProtected(permissions.ManageReferenceTypes,
'unregisterReferenceType')
def unregisterReferenceType(self, portal_type):
"""Remove portal_type from the list that should be considered
references for this plone instance. Do not fail if the type is not
already registered.
"""
# self._reference_types is a PersistentMapping
try:
del self._reference_types[portal_type]
except KeyError:
pass
security.declarePublic('getImportFormatNames')
示例7: address
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
#.........这里部分代码省略.........
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
def unconfirmed_email_list(self):
return self.__unconfirmed.keys()
def set_primary_email(self, email):
email = email.lower()
if self.has_email(email):
self.primary_email = email
else:
raise ValueError("I don't know email <%s>" % email)
def get_primary_email(self):
return self.primary_email
def notify_email_confirmed(self, email):
"""Notice that email was just confirmed."""
pass
def _consistency_check(self):
if self.primary_email is not None:
if self.primary_email not in self.__items:
raise KeyError, "primary_email not in email list"
typecheck_seq(self.__items, str, allow_none=1)
示例8: ACL
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
class ACL(Persistent):
""" Access control hub. The ACL can be instantiated and added to, say
the root object, with attribute name acl. """
def __init__(self, settings):
self.users = PersistentMapping()
self.groups = PersistentMapping()
self.activation = PersistentMapping()
admin, pwd = settings.get('pycms.admin_user',
"admin:admin").split(":")
self.users['admin'] = User(admin, "Administrator", "", pwd)
self.groups['admin'] = Group('admin', users=PersistentList(['admin']))
self.groups['viewers'] = Group('viewers')
self.groups['editors'] = Group('editors')
def generate_user_invite_key(self, user_id):
""" Generate unique registration key for user and set on user. """
if not user_id in self.users:
return None
t1 = time.time()
time.sleep(random.random())
t2 = time.time()
base = hashlib.md5(str(t1 + t2))
key = base.hexdigest()[:KEY_LENGTH]
self.activation[key] = self.users[user_id]
return key
def get_user_for_activation(self, key):
return self.activation.get(key, None)
def unset_activation_key(self, key):
if key in self.activation:
del self.activation[key]
def list_users(self):
""" Return a dict of users, using the id as key """
return self.users.keys()
def list_groups(self):
return self.groups.keys()
def update_user(self, **data):
self.users[data['email']].name = data['name']
if data.get('pwd', None):
self.users[data['email']].set_pwd(data['pwd'])
def set_user_groups(self, user_id, groups=[]):
""" Remove user from all groups, and then reset..."""
for group_id in self.groups.keys():
self.rm_user_from_group(group_id, user_id)
for group_id in groups:
self.add_user_to_group(group_id, user_id)
def rm_user_from_group(self, group_id, user_id):
if user_id in self.groups[group_id].users:
idx = self.groups[group_id].users.index(user_id)
del self.groups[group_id].users[idx]
def add_user_to_group(self, group_id, user_id):
if not user_id in self.groups[group_id].users:
self.groups[group_id].users.append(user_id)
def create_user(self, email, pwd=None, name='', profile=None):
if email in self.users:
return None
self.users[email] = User(email, name or email,
email, pwd,
profile=profile)
return self.users[email]
def remove_user(self, user_id):
if user_id in self.users:
del self.users[user_id]
示例9: __init__
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
class ContentGroupManager:
""" """
def __init__(self):
self.__groups_collection = PersistentMapping()
def __add_group_item(self, id, name, filter, pattern):
#create a new item
item = ContentGroup(id, name, filter, pattern)
self.__groups_collection[id] = item
def __update_group_item(self, id, name, filter, pattern):
#modify an item
item = self.__groups_collection.get(id)
if item is not None:
item.name = name
item.filter = filter
item.pattern = pattern
self.__groups_collection[id] = item
def __delete_group_item(self, id):
#delete an item
try: del(self.__groups_collection[id])
except: pass
#################
# BASIC API #
#################
def get_groups_collection(self):
#return the groups collection
return self.__groups_collection
def get_groups_ids(self):
#get the groups ids
return self.__groups_collection.keys()
def get_groups_list(self):
#get a list with all items
return utils.utSortObjsListByAttr(self.__groups_collection.values(), 'name')
def get_group_item(self, id):
#get an item
try: return self.__groups_collection[id]
except: return None
def get_group_item_data(self, id):
#get an item data
item = self.get_group_item(id)
if item is not None:
return ['update',
item.id,
item.name,
item.filter,
item.pattern,
item.start,
item.maxResults,
item.g_filter,
item.restrict,
item.safeSearch,
item.language,
item.inputencoding,
item.outputencoding,
item.http_proxy,
item.search_type]
else:
return ['add', '', '', '', '']
def add_group_item(self, id, name, filter, pattern):
#create a new item
self.__add_group_item(id, name, filter, pattern)
def update_group_item(self, id, name, filter, pattern):
#modify an item
self.__update_group_item(id, name, filter, pattern)
def update_google_props(self, id, start, maxResults, filter, restrict, safeSearch,
language, inputencoding, outputencoding, http_proxy):
#update the Google search properties
msg = 0
item = self.__groups_collection.get(id)
if item is not None:
#set data
try:
#check if integer values
start = int(start)
maxResults = int(maxResults)
filter = int(filter)
safeSearch = int(safeSearch)
except:
msg = 1
if not msg:
#set data
item.start = start
item.maxResults = maxResults
item.g_filter = filter
item.safeSearch = safeSearch
item.restrict = restrict
item.language = language
item.inputencoding = inputencoding
#.........这里部分代码省略.........
示例10: NounBayesClassifier
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
class NounBayesClassifier(Persistent):
"""
"""
implements(IContentClassifier)
def __init__(self,tagger=None,noNounRanksToKeep = 20):
"""
"""
self.noNounRanksToKeep = noNounRanksToKeep
self.trainingDocs = PersistentMapping()
self.allNouns = OOSet()
self.classifier = None
self.trainAfterUpdate = True
def addTrainingDocument(self,doc_id,tags):
"""
"""
storage = getUtility(INounPhraseStorage)
importantNouns = storage.getNounTerms(doc_id,self.noNounRanksToKeep)
self.trainingDocs[doc_id] = (importantNouns,tags)
self.allNouns = union(self.allNouns,OOSet(importantNouns))
def train(self):
"""
"""
presentNouns = dict()
trainingData = []
if not self.allNouns:
storage = getUtility(INounPhraseStorage)
for key in self.trainingDocs.keys():
importantNouns = storage.getNounTerms(
key,
self.noNounRanksToKeep)
self.allNouns = union(self.allNouns,OOSet(importantNouns))
for item in self.allNouns:
presentNouns.setdefault(item,0)
for (nouns,tags) in self.trainingDocs.values():
nounPresence = presentNouns.copy()
for noun in nouns:
nounPresence[noun] = 1
for tag in tags:
trainingData.append((nounPresence,tag,))
if trainingData:
self.classifier = NaiveBayesClassifier.train(trainingData)
def classify(self,doc_id):
"""
"""
if not self.classifier:
return []
presentNouns = dict()
for item in self.allNouns:
presentNouns.setdefault(item,0)
storage = getUtility(INounPhraseStorage)
importantNouns = storage.getNounTerms(doc_id,self.noNounRanksToKeep)
for noun in importantNouns:
if noun in presentNouns.keys():
presentNouns[noun] = 1
return self.classifier.classify(presentNouns)
def probabilityClassify(self,doc_id):
"""
"""
if not self.classifier:
return []
presentNouns = dict()
for item in self.allNouns:
presentNouns.setdefault(item,0)
storage = getUtility(INounPhraseStorage)
importantNouns = storage.getNounTerms(doc_id,self.noNounRanksToKeep)
for noun in importantNouns:
if noun in presentNouns.keys():
presentNouns[noun] = 1
return self.classifier.prob_classify(presentNouns)
def clear(self):
"""Wipes the classifier's data.
"""
self.allNouns.clear()
self.trainingDocs.clear()
def tags(self):
if not self.classifier:
return []
return self.classifier.labels()
示例11: CustomField
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
#.........这里部分代码省略.........
[str(x) for x in value]
except ValueError:
return False, u"Not a list of strings"
# check each TALES expression
for ve in self.getValidationExpressions():
ec = self._getExprContext(self, extra_namespaces=dict(value=value))
ex = Expression(ve.expression)
if not bool(ex(ec)):
return False, ve.message
# by default no validation expression made it invalid
return True, None
##
## Working with the persistent attributes
##
def getCoreAttribute(self, *key_and_default):
""" return the value of this attribute. If len(@key_and_default) = 2 is
the second one is a default value. If not don't fall back on a default.
"""
if not len(key_and_default) in (1, 2):
raise ValueError, "Call getCoreAttribute(key [,default])"
if len(key_and_default) == 1:
return self.attributes[key_and_default[0]]
else:
return self.attributes.get(key_and_default[0], key_and_default[1])
security.declareProtected(VMS, "getCoreAttributeKeys")
def getCoreAttributeKeys(self):
return list(self.attributes.keys())
security.declareProtected(VMS, "getCoreAttributeKeyLabel")
def getCoreAttributeKeyLabel(self, key, html_ok=False):
""" return a string that explains what the key is.
The resturn string can contain HTML.
"""
if key == "dom_id":
if html_ok:
return u'<abbr title="DOM element ID, not Zope object ID">DOM ID</abbr>'
else:
return u"DOM ID"
if key.startswith("on") and re.findall("on\w+", key):
return u"on" + key[2:].capitalize()
if key in ("rows", "cols"):
return u"Textarea %s" % key
return key.title()
def getCoreAttributeKeySuggestions(self):
""" return a list of suggestions of attribute keys you might want to add """
suggestions = ["style", "size", "dom_id", "onchange", "onkeypress", "onclick", "onfocus", "onblur", "value"]
# add more
if self.input_type == "textarea":
suggestions.append("cols")
suggestions.append("rows")
elif self.input_type == "select":
suggestions.append("multiple")
# reduce already used ones
示例12: Box
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [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.
#.........这里部分代码省略.........
示例13: Item
# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import keys [as 别名]
#.........这里部分代码省略.........
break
folder_parent = folder_parent.parent
return parents
def is_folder_in_parents(self, folder_item):
"""
Check whether i am in the hierarchy tree of folder
for example /a/folder/v/c/item
@param folder_item: Folder
@return: boolean
"""
if not isinstance(folder_item, folder.Folder):
return False
# go through my parents and try to find folder
folder_parent = self.parent
# go through the hierarchy of my parents and try to find folder
while folder_parent:
if folder_item == folder_parent:
return True
folder_parent = folder_parent.parent
return False
# properties operations
def __getitem__(self, key):
return self.get_property(key)
def __delitem__(self, key):
if key in self.__properties.keys():
del self.__properties[key]
self.mark_changed()
def __setitem__(self, key, value):
self.set_property(key, value)
def has_property(self, name):
return name in self.__properties
def get_property(self, name, default=None):
if name in ('name', 'id', 'title', 'description', 'created', 'modified'):
return getattr(self, name)
if name in self.__properties:
return self.__properties[name]
return default
def set_property(self, name, value):
if self.is_string(name, raise_err=True):
self.__properties[name] = value
self.mark_changed()
def get_properties(self, properties):
if not properties:
return []
if not isinstance(properties, (list, tuple)):
raise TypeError('properties must be list or tuple received: %s' % type(properties))
view = {}