def notifications(self, value): # check that value is list if not isinstance(value, list): raise Exception("Notifcations should be list of dictionaries, " "that can be dumped using json module.") # check that all list items are dictionaries for item in value: if not isinstance(item, dict): raise Exception("Notifcations should be list of dictionaries, " "that can be dumped using json module.") # check that we can dump value using json module try: json.dumps(value) except: raise Exception("Notifcations should be list of dictionaries, " "that can be dumped using json module.") # if assignee is storing notifications then we store to annotations current = api.user.get_current().getId() assignee = getattr(self.context, 'assignee', None) if assignee and current in assignee: annotations = self._setup_annotations() rules = PersistentList() for item in value: rules.append(PersistentDict(item)) annotations[TASK_NOTIFICATIONS_KEY][current] = rules # otherwise we store else: setattr(self.context, 'notifications', value) self.context.reindexObject()
class Activity(BehavioralFlowNode, EventHandler): def __init__(self, definition): super(Activity, self).__init__(definition) self.assigned_to = PersistentList() def assigne_to(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if not(u in self.assigned_to)] self.assigned_to.extend(users) def unassigne(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if (u in self.assigned_to)] for user in users: self.assigned_to.remove(user) def set_assignment(self, users=None): self.assigned_to = PersistentList() if users is not None: self.assigne_to(users)
def __init__(self, name='', group=None): Watchable.__init__(self) self.group = group self.name = name self.modified = never self.__items = PersistentList() self.__categories = PersistentList()
class SubProcess(Activity): def __init__(self, definition): super(SubProcess, self).__init__(definition) self.sub_processes = PersistentList() def _start_subprocess(self, action): def_container = find_service('process_definition_container') pd = def_container.get_definition(getattr(self.definition.sub_process_definition, 'id', self.definition.sub_process_definition)) proc = pd() proc.__name__ = proc.id runtime = find_service('runtime') runtime.addtoproperty('processes', proc) proc.defineGraph(pd) self.definition._init_subprocess(self.process, proc) proc.attachedTo = action proc.execute() self.sub_processes.append(proc) return proc def stop(self): runtime = find_service('runtime') for process in self.sub_processes: process._finished = True for node in process.nodes: node.stop() node.setproperty('workitems', []) runtime.delfromproperty('processes', process)
def _process(self): if self._target.isClosed(): return json.dumps({'status': 'error'}, textarea=True) else: if self._tempFilePath is not None: if self._conf.getPosterTemplateManager().hasTemplate(self.__templateId): # Save backgroundId = self._conf.getPosterTemplateManager().getTemplateById(self.__templateId).addTempBackgroundFilePath(self._tempFilePath,self._bgPosition) else: # New key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId) value = session.get(key) if value is None: # First background tempFilePathList = PersistentList() tempFilePathList.append((self._tempFilePath,self._bgPosition)) session[key] = tempFilePathList backgroundId = 0 else: # We have more value.append((self._tempFilePath, self._bgPosition)) backgroundId = len(value) - 1 session.modified = True return json.dumps({ 'status': 'OK', 'id': backgroundId, 'url': str(urlHandlers.UHConfModifPosterGetBackground.getURL(self._conf, self.__templateId, backgroundId)), 'pos': self._bgPosition }, textarea=True)
class Sponsored(HasState): """Mixin class for sponsored objects. Refactored out of Voteable. """ def __init__(self, min_sponsors=1): HasState.__init__(self) self.min_sponsors = min_sponsors self.__sponsors = PersistentList() def add_sponsor(self, sponsor): if sponsor not in self.__sponsors: self.__sponsors.append(sponsor) def get_sponsors(self): return self.__sponsors def enough_sponsors(self): return len(self.__sponsors) >= self.min_sponsors def set_pending(self): """Transition from new to pending state. Awaiting more sponsors.""" if self.get_state() != 'new': raise InvalidState, "cannot transition to pending from '%s' state." % self.get_state() self.set_state('pending') def force_accept(self): """Force into accepted state, regardless of vote or status.""" self.set_state('accepted') def is_sponsor(self, user): return user in self.__sponsors
class CustomizationMarker(PersistentInterfaceClass, ZMIObject): meta_type = "Silva Customization Marker" silvaconf.icon("markers.png") silvaconf.factory("manage_addCustomizationMarkerForm") silvaconf.factory("manage_addCustomizationMarker") def __init__(self, name, doc=None): self.id = name PersistentInterfaceClass.__init__(self, name=name, bases=(ICustomizableMarker,), __doc__=doc) ZMIObject.__init__(self) self.marked = PersistentList() def updateIdentifier(self): self.__identifier__ = self.markerId() def addMarkedObject(self, obj): oid = getUtility(IIntIds).register(obj) self.marked.append(oid) def removeMarkedObject(self, obj): oid = getUtility(IIntIds).getId(obj) self.marked.remove(oid) def markedObjects(self): resolver = getUtility(IIntIds).getObject return [resolver(oid) for oid in self.marked] def markerId(self): return u"marker:%s" % ".".join(self.getPhysicalPath()[1:])
def __init__(self): self.associations=OOBTree() self.handles=OOBTree() self.nonces=OITreeSet() self.noncetimeline=PersistentList() self.assoctimeline=PersistentList()
def __init__(self): self.__bank = self.initial_bank self.__subpoints = 0 self.__plus_given = 0 self.__minus_given = 0 self.__plus_given_to = PersistentList() self.__minus_given_to = PersistentList()
def __init__(self, **kwargs): super(Wizard, self).__init__(**kwargs) self.transitionsinstances = PersistentList() self.stepinstances = PersistentList() for key, step in self.steps.items(): stepinstance = step(step_id=key, wizard=self) self.stepinstances.append((stepinstance.step_id, stepinstance)) _stepinstances = dict(self.stepinstances) for transition in self.transitions: sourceinstance = _stepinstances[transition[0]] targetinstance = _stepinstances[transition[1]] transitionid = transition[0]+'->'+transition[1] condition = None try: condition = transition[3] except Exception: condition = default_condition default = False try: default = transition[2] except Exception: pass transitioninstance = Transition(sourceinstance, targetinstance, transitionid, condition, default) self.transitionsinstances.append((transitionid, transitioninstance))
class MockMailHost(MailBase): """A MailHost that collects messages instead of sending them. """ def __init__(self, id): self.reset() def reset(self): self.messages = PersistentList() def _send(self, mfrom, mto, messageText, immediate=False): """ Send the message """ self.messages.append(messageText) def send(self, messageText, mto=None, mfrom=None, subject=None, encode=None, immediate=False, charset=None, msg_type=None): messageText, mto, mfrom = _mungeHeaders(messageText, mto, mfrom, subject, charset=charset, msg_type=msg_type) self.messages.append(messageText) # Outside of the tests we patch the MailHost to provide a # secureSend method for backwards compatibility, so we should do # that for our MockMailHost as well. secureSend = secureSend
def replace_values(obj, orig, new): """ replace all occurences of column name """ if isinstance(obj, PersistentList) or isinstance(obj, list): if isinstance(obj, PersistentList): new_obj = PersistentList() else: new_obj = [] for item in obj: new_item = replace_values(item, orig, new) new_obj.append(new_item) return new_obj if isinstance(obj, PersistentDict) or isinstance(obj, dict): if isinstance(obj, PersistentDict): new_obj = PersistentDict() else: new_obj = {} for key in obj.keys(): new_value = replace_values(obj[key], orig, new) new_key = replace_values(key, orig, new) new_obj[new_key] = new_value return new_obj if isinstance(obj, basestring): new_obj = obj.replace(orig, new) return new_obj return obj
class DBList(MutableSequence, Persistent): def __init__(self, source=None): self.plist = ZPersistentList() if source is not None: self.extend(source) # TODO: extend the plist instead, after # validating the types of the items in source def __getitem__(self, index): return self.plist[index] def __setitem__(self, index, value): if not isinstance(value, (basestring, int, long, bool, type(None), DBDict, DBList)): raise TypeError("Values can only be those supported by the ZODB backend.") self.plist[index] = value def __delitem__(self, index): del self.plist[index] def insert(self, index, value): if not isinstance(value, (basestring, int, long, bool, type(None), DBDict, DBList)): raise TypeError("Values can only be those supported by the ZODB backend.") self.plist.insert(index, value) def __len__(self): return len(self.plist) def __iter__(self): return self.plist.__iter__() def __contains__(self, value): return self.plist.__contains__(value)
class Response(Persistent): implements(IResponse) def __init__(self, text): self.__parent__ = self.__name__ = None self.text = text self.changes = PersistentList() sm = getSecurityManager() user = sm.getUser() self.creator = user.getId() or '(anonymous)' self.date = DateTime() self.type = 'additional' self.mimetype = '' self.rendered_text = None self.attachment = None def add_change(self, id, name, before, after): """Add a new issue change. """ delta = dict( id=id, name=name, before=before, after=after) self.changes.append(delta)
class Response(Persistent): implements(IResponse) def __init__(self, text): self.__parent__ = self.__name__ = None self.text = text self.changes = PersistentList() sm = getSecurityManager() user = sm.getUser() self.creator = user.getId() or '(anonymous)' self.date = DateTime() self.type = 'additional' self.mimetype = '' self.rendered_text = None self.relatedItems = () self.added_object = None self.successor_oguid = None self.transition = None def add_change(self, id, name, before, after): """Add a new issue change. """ delta = dict( id=id, name=name, before=before, after=after) self.changes.append(delta) def creator_link(self): info = getUtility(IContactInformation) return info.render_link(self.creator)
class MailingListManager(SimpleItem): implements(IMailingListManager) def __init__(self): self.mailinglists = PersistentList() self.id_seed = 0 def add(self, name, email, protocol): self.id_seed += 1 self.mailinglists.append({'id': self.id_seed, 'name': name, 'email': email, 'protocol': protocol}) def remove(self, list_id): self.mailinglists = filter(lambda l: str(l['id']) != list_id, self.mailinglists) def get_mailinglist_by_id(self, list_id): for mlist in self.mailinglists: if str(mlist['id']) == str(list_id): return mlist return None @property def protocols(self): return [{'id': 'mailman', 'name': 'Mailman'}, {'id': 'google_groups', 'name': 'Google Groups'}, {'id': 'sympa', 'name': 'Sympa'}]
class SponsoredQueue(QonPersistent): """A queue to keep Sponsored items that are in pending state. Code refactored out of Voteable. """ def __init__(self): self.queue = PersistentList() def add_to_queue(self, item): self.queue.append(item) def remove_from_queue(self, item): if item in self.queue: self.queue.remove(item) def add_sponsor(self, item, sponsor): """Add sponsor to item.""" item.add_sponsor(sponsor) if item.enough_sponsors(): self.force_accept(item) def get_items_by_state(self, state): items = [item for item in self.queue if item.get_state() == state] return items def new_items(self): return self.get_items_by_state('new') def pending_items(self): return self.get_items_by_state('pending') def force_accept(self, item): item.force_accept() self.remove_from_queue(item)
def journal_entry_factory(context, action, title, visible=True, comment='', actor=None, documents=None): if actor is None: actor = api.user.get_current().getId() comment = comment == '' and get_change_note(getRequest(), '') or comment title = propper_string(title) action = propper_string(action) comment = propper_string(comment) action_entry = PersistentDict({'type': action, 'title': title, 'visible': visible}) if documents: action_documents = PersistentList() for doc in documents: action_documents.append(PersistentDict( {'id': Oguid.for_object(doc).id, 'title': doc.title})) action_entry['documents'] = action_documents entry = { 'obj': context, 'action': action_entry, 'actor': actor, 'comment': comment} notify(JournalEntryEvent(**entry))
def test_prevents_bad_string_formatting_key(self): from AccessControl.safe_formatter import SafeFormatter from AccessControl.ZopeGuards import guarded_getitem from persistent.list import PersistentList # Accessing basic Python types in a basic Python list is fine. foo = list(['bar']) self.assertEqual(SafeFormatter('{0[0]}').safe_format(foo), 'bar') self.assertEqual(guarded_getitem(foo, 0), 'bar') # For basic Python types in a non-basic list, we guard the access. foo = PersistentList(foo) self.assertRaises(Unauthorized, guarded_getitem, foo, 0) self.assertRaises(Unauthorized, SafeFormatter('{0[0]}').safe_format, foo) # though we could allow access if we want: foo.__allow_access_to_unprotected_subobjects__ = 1 self.assertEqual(guarded_getitem(foo, 0), 'bar') self.assertEqual(SafeFormatter('{0[0]}').safe_format(foo), 'bar') # For non-basic items we want run checks too. folder = self._create_folder_with_mixed_contents() # We can get the public items just fine: self.assertEqual(SafeFormatter('{0[0]}').safe_format(folder), '<Item public1>') self.assertEqual(SafeFormatter('{0[2]}').safe_format(folder), '<Item public2>') # But not the private item: self.assertRaises(Unauthorized, SafeFormatter('{0[1]}').safe_format, folder)
def _process(self): if self._target.isClosed(): return json.dumps({'status': 'error'}, textarea=True) else: if self._tempFilePath is not None: if self._conf.getBadgeTemplateManager().hasTemplate(self.__templateId): backgroundId = self._conf.getBadgeTemplateManager().getTemplateById(self.__templateId).addTempBackgroundFilePath(self._tempFilePath) else: key = "tempBackground-%s-%s" % (self._conf.id, self.__templateId) value = session.get(key) if value is None: tempFilePathList = PersistentList() tempFilePathList.append(self._tempFilePath) session[key] = tempFilePathList backgroundId = 0 else: value.append(self._tempFilePath) backgroundId = len(value) - 1 session.modified = True return json.dumps({ 'status': 'OK', 'id': backgroundId, 'url': str(urlHandlers.UHConfModifBadgeGetBackground.getURL(self._conf, self.__templateId, backgroundId)) }, textarea=True)
def __call__(self): term = getTermForDate(self.event.date) if term is None: return old_date = self.event.date new_date = self.event.replacement_date schoolyear = ISchoolYear(term) timetables = ITimetableContainer(schoolyear) for timetable in timetables.values(): if IScheduleExceptions.providedBy(timetable): modified = False scheduled = DateRange(timetable.first, timetable.last) meeting_exceptions = PersistentList() if old_date in scheduled: meetings = list(timetable.iterMeetings(old_date)) for meeting in meetings: meeting_exceptions.append( MeetingException( meeting.dtstart.replace(year=new_date.year, month=new_date.month, day=new_date.day), meeting.duration, period=meeting.period, meeting_id=meeting.meeting_id)) timetable.exceptions[old_date] = PersistentList() modified = True if new_date in scheduled: timetable.exceptions[new_date] = meeting_exceptions modified = True if modified: zope.lifecycleevent.modified(timetable)
class GenericContainer(grok.Container): def __init__(self, name, id=None): super(GenericContainer, self).__init__() self.name = name self.id = id self.item_count = 0 self.item_order = PersistentList() def items(self): t = [] for key in self.item_order: t.append(self[unicode(key)]) return t def inverse_items(self): t = self.items() t.reverse() return t def delete(self,id): self.item_order.pop(self.item_order.index(int(id))) def add_item(self,item): self[unicode(self.item_count)] = item self.item_order.append(self.item_count) self.item_count += 1 def max(self): if self.items() is not None: return self.items()[-1] def min(self): if self.items is not None: return self.items()[0]
def __init__(self): self.__activity = UserActivity() self.__anon_can_read_blog = False self.__member_since = datetime.utcnow() self.__top_activity_thresh = 2 self.__contact_names = PersistentList() self.__notes = PersistentList() self.__total_pms_sent = 0
def notify_personal_news_added(self, item): """Notice that a personal news item (BlogItem) was created.""" plist = self.__recent_personal_news if not plist: plist = PersistentList() plist.append(item) plist = plist[-self._personal_news_count:] self.__recent_personal_news = plist
def __init__(self, deployment, name): self.name = name self.deployment = deployment self.versions = PersistentList() self.instances = PersistentList() self.held = False self.hold_message = None
def add_comment(self, comment): if not self.__comments: self.__comments = PersistentList() if not self.__comment_flags: self.__comment_flags = PersistentList() self.__comments.append(comment) self.__comment_flags.append(0)
def serialize_users(self): """Returns a persistent list of dicts for all users. """ value = PersistentList() for item in self.users: value.append( PersistentDict({'id': item.id, 'title': item.get_title()})) return value
def cancel_karma_given(self): """Admin function to cancel all karma given to users (HasKarma) by self.""" for u in self.karma_plus_given_to() + self.karma_minus_given_to(): u.return_karma_from(self) # zero lists self.__plus_given_to = PersistentList() self.__minus_given_to = PersistentList()
def __init__(self, default_value, filters=None): """ Create a datatype, where default_value is the initial value to be wrapped. Filters are a list of lambda expressions used to evaluate the contents post-update """ self.value = default_value l = PersistentList() if filters: [l.append(f) for f in filters] self.filters = l
def serialize_contacts(self): """Returns a persistent list of dicts for all contacts. """ value = PersistentList() for item in self.contacts: value.append( PersistentDict({'id': item.get_contact_id(), 'title': item.get_title()})) return value
def get_storage(obj): """Get or create the audit log storage for the given object :param obj: Content object :returns: PersistentList """ annotation = IAnnotations(obj) if annotation.get(SNAPSHOT_STORAGE) is None: annotation[SNAPSHOT_STORAGE] = PersistentList() return annotation[SNAPSHOT_STORAGE]
class Step(object): def __init__(self, **kwargs): super(Step, self).__init__() self.wizard = None if 'wizard' in kwargs: self.wizard = kwargs['wizard'] self.step_id = '' if 'step_id' in kwargs: self.step_id = kwargs['step_id'] self._outgoing = PersistentList() self._incoming = PersistentList() def add_outgoing(self, transition): self._outgoing.append(transition) def add_incoming(self, transition): self._incoming.append(transition)
def index_parent_child(self, parent, child=None): if ITracTicket.providedBy(parent): parent = parent.getId() if ITracTicket.providedBy(child): child = child.getId() parent = int(parent) child = int(child) if child else None self._children[parent] = self._children.get(parent, PersistentList()) if child is not None: self._children[parent].append(child)
def start(self, context, request, appstruct, **kw): timezone = pytz.timezone(context.tzname) context.date = context.date.replace(tzinfo=timezone) context.state = PersistentList(['published']) context.update() context.format(request) context.reindex() request.registry.notify( ActivityExecuted(self, [context], get_current(request))) return {}
def start(self, context, request, appstruct, **kw): context.state = PersistentList(['active']) today = datetime.datetime.now(tz=pytz.UTC) end_date = context.end_date.replace(tzinfo=pytz.UTC) start_date = today if today > end_date else end_date context.end_date = (datetime.timedelta(days=30) + \ start_date).replace(tzinfo=pytz.UTC) context.modified_at = today context.reindex() return {}
def test_persistent_list(self): value = PersistentList(["foo"]) self.assertEqual(["foo"], json_compatible(value)) self.assertEqual('["foo"]', json.dumps(json_compatible(value))) self.assertIsInstance( json_compatible(value)[0], six.text_type, "PersistentList values should be converted" " recursively.", )
def test_blacklisting_recursive_children_does_not_affect_parents(self): config = IConfig(self.portal) config.setPathBlacklist(PersistentList()) config.appendPathToBlacklist('/foo/bar/one/*') blacklist = IPathBlacklist(self.portal) self.assertFalse(blacklist.is_blacklisted('/foo/bar')) self.assertTrue(blacklist.is_blacklisted('/foo/bar/one/two')) self.assertFalse(blacklist.is_blacklisted('/foo/bar/oneXXXXX')) self.assertTrue(blacklist.is_blacklisted('/foo/bar/one/two/three'))
def test_blacklisting_trailing_wildcards_does_not_affect_parents(self): config = IConfig(self.portal) config.setPathBlacklist(PersistentList()) config.appendPathToBlacklist('/foo/bar/one*') blacklist = IPathBlacklist(self.portal) self.assertFalse(blacklist.is_blacklisted('/foo/bar')) self.assertTrue(blacklist.is_blacklisted('/foo/bar/one')) self.assertFalse(blacklist.is_blacklisted('/foo/bar/one/two')) self.assertTrue(blacklist.is_blacklisted('/foo/bar/oneXXXX'))
def add_event_to_history(obj, history_attr, action, actor=None, time=None, comments=u'', extra_infos={}): '''This is an helper method to add an entry to an history.''' if not base_hasattr(obj, history_attr): setattr(obj, history_attr, PersistentList()) history_data = {'action': action, 'actor': actor and actor.getId() or api.user.get_current().getId(), 'time': time or DateTime(), 'comments': comments} history_data.update(extra_infos) getattr(obj, history_attr).append(history_data.copy())
def __init__(self, name, users): Persistent.__init__(self) self.key = users.maxKey() + 1 self.__parent__ = users self.__name__ = self.key self.name = name self._passHash = "" self._groups = PersistentList() self.contact = None users[self.key] = self
def __call__(self): local_tz = get_localzone() annotations = IAnnotations(self.portal) touched_store = annotations.get(RECENTLY_TOUCHED_KEY) if not touched_store: return for userid in touched_store.keys(): temp_entry_list = PersistentList() for entry in touched_store[userid]: naive_touched_date = entry['last_touched'] entry['last_touched'] = naive_touched_date.replace( tzinfo=local_tz) # Replace the list with a copy of the list but # using persistent mappings. temp_entry_list.append(PersistentMapping(entry)) touched_store[userid] = temp_entry_list
def publish_organizations(root, registry): from novaideo.views.filter import find_entities from novaideo.content.interface import IOrganization contents = find_entities(interfaces=[IOrganization]) for org in contents: org.state = PersistentList(['published']) org.reindex() log.info('Orgnaizations evolved.')
def __init__( self, firstname='', lastname='', email='', phone='', extension='', fax='', department='', position='', organization='', location='', country='', websites=None, languages='', office='', room_no='', biography='', date_format=None, data=None, home_path=None, preferred_communities=None, ): super(Profile, self).__init__(data) self.firstname = firstname self.lastname = lastname self.email = email self.phone = phone self.fax = fax self.extension = extension self.department = department self.position = position self.organization = organization self.location = location if country not in countries.as_dict: country = 'XX' self.country = country if websites is not None: self.websites = websites self.languages = languages self.office = office self.room_no = room_no self.biography = biography if date_format not in cultures.as_dict: date_format = None self.date_format = date_format self.home_path = home_path self._alert_prefs = PersistentMapping() self._pending_alerts = PersistentList() self.categories = PersistentMapping() self.password_reset_key = None self.password_reset_time = None self.preferred_communities = preferred_communities self.last_login_time = None self.last_chatter_query = None
def create(self, order): """ generates an order from the cart """ member = getMultiAdapter((self.context, self.context.REQUEST), name=u'plone_portal_state').member() cart = interfaces.IShoppingCart(self.context) if not len(cart): return order.userid = member.getId() order.date = time() order.currency = CurrencyAware(0).getCurrencySymbol() products = cart.getProducts() order_products = PersistentList() price = 0 for product in products: price += product['price_raw'] * product['amount'] order_products.append( (product['uid'], product['no'], product['title'], product['amount'], product['price_raw'], [ (variation['uid'], variation['type'], variation['name']) for variation in product['variations'] ])) if order_products != order.products: order.processed_steps = () order.products = order_products order.price = price order._taxincl = interfaces.ITaxes(self.context).taxincl pretaxcharges = [] providers = getAdapters((self.context, ), interfaces.IPreTaxCharge) for name, provider in providers: pretaxcharges.append(provider.process(order)) order.pretaxcharges = tuple(pretaxcharges) posttaxcharges = [] providers = getAdapters((self.context, ), interfaces.IPostTaxCharge) for name, provider in providers: posttaxcharges.append(provider.process(order)) order.posttaxcharges = tuple(posttaxcharges) self[order.orderid] = order
def is_expired(self): if 'expired' not in self.state: now = datetime.datetime.now(tz=pytz.UTC) end_date = getattr(self, 'end_date', now).replace(tzinfo=pytz.UTC) if end_date <= now: self.state = PersistentList(['expired']) return True return False return True
def test_portal_can_be_blacklisted(self): config = IConfig(self.portal) config.setPathBlacklist(PersistentList()) blacklist = IPathBlacklist(self.portal) # The portal is not blacklisted by default. self.assertFalse(blacklist.is_blacklisted(self.portal)) # Blacklist the portal. config.appendPathToBlacklist('/'.join(self.portal.getPhysicalPath())) self.assertTrue(blacklist.is_blacklisted(self.portal))
def store(self, key, value): key = self._normalize_key(key) if not isinstance(value, PersistentMapping): value = PersistentMapping(value) self._data_cache[key] = value ## content-UID to keys, used by self.select(), ## self.reload(), and self.invalidate() for uid in (key[0], key[2]): if not self._content_keys.get(uid): self._content_keys[uid] = PersistentList() self._content_keys[uid].append(key)
def __init__(self): self.name = "New Method" self.short_name = "New Method" self.description = "" self.__name__ = Coding().generateUniqueCode(short=True, withdash=False) self.settings = PersistentMapping() self.enabled = False self.public = True self.deadlined = False self.transaction_properties = PersistentMapping() self.groups = PersistentList()
def test_item_can_be_added_to_blacklist(self): config = IConfig(self.portal) config.setPathBlacklist(PersistentList()) # The blacklist is empty by default. self.assertEqual(0, len(config.getPathBlacklist())) # Items can be added to the blacklist. config.appendPathToBlacklist('hans') self.assertIn('hans', config.getPathBlacklist()) self.assertEqual(1, len(config.getPathBlacklist()))
def make_config_persistent(kwargs): """ iterates on the given dictionary and replace list by persistent list, dictionary by persistent mapping. """ for key, value in kwargs.items(): if type(value) == type({}): p_value = PersistentMapping(value) kwargs[key] = p_value elif type(value) in (type(()), type([])): p_value = PersistentList(value) kwargs[key] = p_value
def onItemModification(self, obj): """ sends notifications """ if self.auto_subscribe: # we don't check if user is already in dict because addSubscriber method do this mtool = getToolByName(self, 'portal_membership') memberid = mtool.getAuthenticatedMember().getId() conv = obj.getConversation() self.addSubscriber(conv, memberid) self.pending.append(self.getObjId(obj)) now = int(time()) #! This method insn't the best. #! It should be better to use Products.cron4plone to send more regularly if self.last_sent and (now - self.last_sent) < self.send_interval: return #! When treating pending objects, current user can have Unauthorized exception when accessing unauthorized objects. #! We don't manage that a recent subscriber could receive a comment posted before he subscribes (when responding at this comment by example) self.process_pending() self.last_sent = now self.pending = PersistentList()
class TestBodyPartGraph(BodyPartGraph): "Create a BPG containing num_bodyparts BodyParts" def __init__(self, network_args, num_bodyparts, jtype='hinge'): debug('TestBpg.__init__') self.bodyparts = PersistentList() self.unrolled = 0 debug('Creating %d random BodyParts' % (num_bodyparts)) p = TestBodyPart(network_args, jtype) self.bodyparts.append(p) p.isRoot = 1 self.root = p for _ in range(1, num_bodyparts): bp = TestBodyPart(network_args, jtype) bp.isRoot = 0 self.bodyparts.append(bp) e = Edge(bp, 1, 0) p.edges.append(e) p = bp self.connectInputNodes()
def evolve_state_files(root, registry): from novaideo.views.filter import find_entities from novaideo.content.interface import IFile contents = find_entities(interfaces=[IFile]) for file_ in contents: if not file_.state: file_.state = PersistentList(['draft']) file_.reindex() log.info('Working groups evolved.')
def getPathBlacklist(self): """ Returns a list of paths which are blacklistet and are not touched by the publisher. """ blacklist = self.annotations.get(ANNOTATIONS_PATH_BLACKLIST_KEY, _marker) if blacklist is _marker: blacklist = PersistentList() self.setPathBlacklist(blacklist) return blacklist
def __init__(self, types, source): super().__init__() if not isinstance(types, PersistentList): types = PersistentList(types) # The type of fact (e.g.., "system.user") self.types: PersistentList = types # The original procedure that found this fact self.source: str = source self.hidden: bool = False
def init_informations(self): self.closing_frequence = DEFAULT_CLOSING_FREQUENCE self.delay_before_publication = DEFAULT_DELAY_BEFORE_PUBLICATION self.days_visibility = DEFAULT_DAYS_VISIBILITY self.publication_number = 0 self.closing_date = datetime.datetime.now(tz=pytz.UTC) +\ datetime.timedelta(days=self.closing_frequence) self._tree = PersistentDict() self.keywords = PersistentList() self.tree = DEFAULT_TREE self.init_files()
def start(self, context, request, appstruct, **kw): context.state = PersistentList(['published']) filters = getattr(context, 'filters', []) for filter_ in filters: tree = filter_.get('metadata_filter', {}).get('tree', None) if tree: request.get_site_folder.merge_tree(tree) getSite().merge_tree(tree) context.reindex() return {}
def subscribe_users_notif_ids(root, registry): from novaideo.views.filter import find_entities from novaideo.content.interface import IPerson contents = find_entities(interfaces=[IPerson]) len_entities = str(len(contents)) for index, node in enumerate(contents): node.notification_ids = PersistentList([]) log.info(str(index) + "/" + len_entities) log.info('Channels evolved.')
def update_tiles_list(brain): item = brain.getObject() annotations = IAnnotations(item) old_list = annotations.get('tiles_list', []) if not old_list: return new_list = PersistentList() for tile_infos in annotations.get('tiles_list', []): new_tile = PersistentMapping() new_tile['tile_id'] = tile_infos['tile_id'] new_tile['tile_type'] = tile_infos['tile_type'] new_tile['tile_hidden'] = False new_tile['tile_style'] = '' new_list.append(new_tile) # create new attribute and clear annotations item.tiles_list = PersistentMapping() item.tiles_list['defaultManager'] = new_list del annotations['tiles_list'] logger.info('updated tiles list for: {0}'.format(brain.getPath()))
def restor(self, request): self.context.state = PersistentList( list(self.context.state_befor_censor)) del self.context.state_befor_censor members = [self.context.author] alert('internal', [request.root], members, internal_kind=InternalAlertKind.moderation_alert, subjects=[self.context], alert_kind='object_restor') self.context.reindex()