def decorate_external_object( do_decorate, call_if_not_decorate, decorate_interface, decorate_meth_name, original_object, external_object, registry, # legacy, ignored. pylint:disable=unused-argument request): if do_decorate: for decorator in subscribers((original_object, ), decorate_interface): meth = getattr(decorator, decorate_meth_name) meth(original_object, external_object) if request is NotGiven: request = get_current_request() if request is not None: # Request specific decorating, if given, is more specific than plain object # decorating, so it gets to go last. for decorator in subscribers((original_object, request), decorate_interface): meth = getattr(decorator, decorate_meth_name) meth(original_object, external_object) elif call_if_not_decorate is not NotGiven and call_if_not_decorate is not None: # XXX: This makes no sense. What is this argument even for? call_if_not_decorate(original_object, external_object) return external_object
def validate(self, REQUEST=None, errors=None, data=None, metadata=None): """Validates the form data from the request. """ if errors is None: errors = {} self.pre_validate(REQUEST, errors) for pre_validator in subscribers((self,), IObjectPreValidation): pre_errors = pre_validator(REQUEST) if pre_errors is not None: for field_name, error_message in pre_errors.items(): if field_name in errors: errors[field_name] += " %s" % error_message else: errors[field_name] = error_message if errors: return errors self.Schema().validate(instance=self, REQUEST=REQUEST, errors=errors, data=data, metadata=metadata) self.post_validate(REQUEST, errors) for post_validator in subscribers((self,), IObjectPostValidation): post_errors = post_validator(REQUEST) if post_errors is not None: for field_name, error_message in post_errors.items(): if field_name in errors: errors[field_name] += " %s" % error_message else: errors[field_name] = error_message return errors
def validate(self): """ Will walk through all subscribers from IValidator type the first one will be returned as valid type. In this way we can supporting a lot of types on the same port/service :return: matched IValidator subscriber """ for sub in subscribers([self.__msg], IValidator): msg = sub.validate() self.is_valid = msg.is_valid self.message_type = msg.message_type self.message = msg.message # we want only one correct type of our message so # only one validator will response with True if self.is_valid is True: self.__logger.debug('Matched type is: {}'.format( self.message_type)) return self self.__logger.warning( 'Main Validator - There are no subscribers from type IValidator') return False
def applyChanges(context, form_fields, data, adapters=None): if adapters is None: adapters = {} changed = False for form_field in form_fields: field = form_field.field # Adapt context, if necessary interface = field.interface adapter = adapters.get(interface) if adapter is None: if interface is None: adapter = context else: adapter = interface(context) adapters[interface] = adapter name = form_field.__name__ newvalue = data.get(name, form_field) # using form_field as marker if (newvalue is not form_field) and (field.get(adapter) != newvalue): changed = True field.set(adapter, newvalue) for handler in component.subscribers( (adapter, field), IFieldUpdate ): handler.update() return changed
def _process_devices(self): stats = {'Device Count': 0, 'Decommissioned Devices': 0, 'CPU Cores':0} LINKED_DEVICES = "Linked Devices" if LINKED_DEVICES not in stats: stats[LINKED_DEVICES] = 0 for device in self._dmd.Devices.getSubDevicesGen_recursive(): stats['Device Count'] += 1 if device.productionState < 0: stats["Decommissioned Devices"] += 1 cpuCount = IDeviceCpuCount(device).cpuCount() log.debug("Devices %s has %s cpu cores", device, cpuCount) stats['CPU Cores'] += cpuCount for adapter in subscribers([device], IDeviceResource): adapter.processDevice(stats) found_linked = False for name, adapter in getAdapters((device,), IDeviceLink): if adapter.linkedDevice(): key = "%s - %s" % (LINKED_DEVICES, name) if key not in stats: stats[key] = 0 stats[key] += 1 if not found_linked: stats[LINKED_DEVICES] += 1 found_linked = True return stats
def __iter__(self): for item in self.previous: keys = list(item.keys()) typekey = self.typekey(*keys)[0] pathkey = self.pathkey(*keys)[0] # integrazione check del tipo all'interno di questo ciclo skip = False for excluded_type in getattr(self, "exclude_type", []): if skip: break # if item is in a blacked-list type, skip it for parent_type in item.get("parents_type_list", []): if parent_type == excluded_type: skip = True break if skip: break # check obj type if item.get("_type", None): if item["_type"] == excluded_type: skip = True if skip: if item.get("_uid") in self.items_in: self.items_in[item.get( "_uid")]["reason"] = "Skipped portal_type" else: self.items_in[item.get("_uid")] = { "id": item.get("_id"), "portal_type": item[typekey], "title": item.get("title"), "path": item.get("_path"), } continue if not (typekey and pathkey): logger.warning("Not enough info for item: {0}".format(item)) yield item continue # custom types mappings handlers = [ x for x in subscribers(( self.context, self.context.REQUEST), IPortalTypeMapping) ] for handler in sorted(handlers, key=lambda h: h.order): item = handler(item=item, typekey=typekey) if item.get("skipped", False): if item.get("_uid") in self.items_in: self.items_in[item.get("_uid")]["reason"] = item.get( "skipped_message", "") else: self.items_in[item.get("_uid")] = { "id": item.get("_id"), "portal_type": item[typekey], "title": item.get("title"), "path": item.get("_path"), } continue yield item
def __call__(self, context): results = [] group_properties = dict() groups = api.group.get_groups() # Fix context if you are using the vocabulary in DataGridField. # See https://github.com/collective/collective.z3cform.datagridfield/issues/31: # NOQA: 501 if not IDexterityContent.providedBy(context): req = getRequest() context = req.PARENTS[0] for group in groups: group_id = group.getId() group_properties[group_id] = { "title": group.getGroupTitleOrName(), "email": group.getProperty("email"), } results = [(id, property["title"]) for id, property in group_properties.items()] # run registered group filter: for subscriber in subscribers([self], IReceiversGroupFilter): results = subscriber.filter(results) # create a list of SimpleTerm items: terms = [] for item in results: terms.append( SimpleTerm(value=item[0], token=item[0], title=item[1])) # Create a SimpleVocabulary from the terms list and return it: return SimpleVocabulary(terms)
def check(self): """ Will trying to get a RootAPI and if match one will fired a process_factory of an implementation API :return: False if not success otherwise the response from process_factory """ for api in subscribers([self.comp], IJSONResourceRootAPI): if api.__class__.__name__.lower() in self.comp.to_dict().keys(): self.__logger.debug('Candidate API {} for {}'.format( api.__class__.__name__, self.comp.__class__.__name__ )) self.__logger.info('Successful apply API {} for {}'.format( api.__class__.__name__, self.comp.__class__.__name__ )) return api.process_factory() return False
def __call__(self): new_user = IUser(self.request) checks = component.subscribers((new_user,), IRedundancyCheck) if any([check.check(new_user, self.request) for check in checks]) or\ not self.context.insert(new_user, check_member=True): return exception_response(409) return HTTPCreated()
def getSubItems(self, context): """Collect all items that should be displayed in the submenu of context. Submenu items are registered as subscribers with interface ISubMenuItem. """ return list(subscribers((context, ), ISubMenuItem))
def transform_obj(target): while True: oid, obj = (yield) # First, get any subscription adapters registered as transforms adapters = subscribers((obj, ), IInvalidationOid) # Next check for an old-style (regular adapter) transform try: adapters = chain(adapters, (IInvalidationOid(obj), )) except TypeError: # No old-style adapter is registered pass transformed = set() for adapter in adapters: o = adapter.transformOid(oid) if isinstance(o, str): transformed.add(o) elif hasattr(o, '__iter__'): # If the transform didn't give back a string, it should have # given back an iterable transformed.update(o) # Get rid of any useless Nones transformed.discard(None) # Get rid of the original oid, if returned. We don't want to use it IF # any transformed oid came back. transformed.discard(oid) target.send(transformed or (oid, ))
def impacts_for(thing): ''' Return a two element tuple. First element is a list of object ids impacted by thing. Second element is a list of object ids impacting thing. ''' try: from ZenPacks.zenoss.Impact.impactd.interfaces import \ IRelationshipDataProvider except ImportError: return ([], []) impacted_by = [] impacting = [] guid_manager = IGUIDManager(thing.getDmd()) for subscriber in subscribers([thing], IRelationshipDataProvider): for edge in subscriber.getEdges(): source = guid_manager.getObject(edge.source) impacted = guid_manager.getObject(edge.impacted) if source == thing: impacted_by.append(impacted.id) elif impacted == thing: impacting.append(source.id) return (impacted_by, impacting)
def impacts_for(thing): ''' Return a two element tuple. First element is a list of object ids impacted by thing. Second element is a list of object ids impacting thing. ''' from ZenPacks.zenoss.Impact.impactd.interfaces \ import IRelationshipDataProvider impacted_by = [] impacting = [] guid_manager = IGUIDManager(thing.getDmd()) for subscriber in subscribers([thing], IRelationshipDataProvider): for edge in subscriber.getEdges(): source = guid_manager.getObject(edge.source) impacted = guid_manager.getObject(edge.impacted) if source.id == thing.id: impacted_by.append(impacted.id) elif impacted.id == thing.id: impacting.append(source.id) return (impacted_by, impacting)
def dispatchToComponent(registration, event): """When a utility is registered, dispatch to an event handler registered for the particular component registered, the registration and the event. """ handlers = subscribers((registration.component, registration, event), None) for handler in handlers: pass # getting them does the work
def deserialize_data(self, data): for root in data: for tab in root.get("items", []): for key in KEYS_WITH_URL: value = tab.get(key, []) if value: tab[key] = [ x.get("UID", "") for x in value if x.get("UID", "") ] blocks = tab.get("blocks", {}) if blocks: for id, block_value in blocks.items(): block_type = block_value.get("@type", "") handlers = [] for h in subscribers( (self.context, self.request), IBlockFieldDeserializationTransformer, ): if ( h.block_type == block_type or h.block_type is None # noqa ): handlers.append(h) for handler in sorted(handlers, key=lambda h: h.order): block_value = handler(block_value) blocks[id] = block_value return data
def validate(self): """ Will walk through all subscribers from IValidator type the first one will be returned as valid type. In this way we can supporting a lot of types on the same port/service :return: matched IValidator subscriber """ for sub in subscribers([self.__msg], IValidator): msg = sub.validate() self.is_valid = msg.is_valid self.message_type = msg.message_type self.message = msg.message # we want only one correct type of our message so # only one validator will response with True if self.is_valid is True: self.__logger.debug('Matched type is: {}'.format(self.message_type)) return self self.__logger.warning('Main Validator - There are no subscribers from type IValidator') return False
def _process_devices(self): stats = { 'Device Count': 0, 'Decommissioned Devices': 0, 'CPU Cores': 0 } LINKED_DEVICES = "Linked Devices" if LINKED_DEVICES not in stats: stats[LINKED_DEVICES] = 0 for device in self._dmd.Devices.getSubDevicesGen_recursive(): stats['Device Count'] += 1 if device.productionState < 0: stats["Decommissioned Devices"] += 1 cpuCount = IDeviceCpuCount(device).cpuCount() log.debug("Devices %s has %s cpu cores", device, cpuCount) stats['CPU Cores'] += cpuCount for adapter in subscribers([device], IDeviceResource): adapter.processDevice(stats) found_linked = False for name, adapter in getAdapters((device, ), IDeviceLink): if adapter.linkedDevice(): key = "%s - %s" % (LINKED_DEVICES, name) if key not in stats: stats[key] = 0 stats[key] += 1 if not found_linked: stats[LINKED_DEVICES] += 1 found_linked = True return stats
def _eventRedispatcher(self, event): """This works similar to zope.component.event.objectEventNotify: It dispatches object events to subscribers that listen to (object, view, event).""" adapters = component.subscribers((event.object, self, event), None) for adapter in adapters: pass # getting them does the work
def transform_obj(target): while True: oid, obj = (yield) # First, get any subscription adapters registered as transforms adapters = subscribers((obj,), IInvalidationOid) # Next check for an old-style (regular adapter) transform try: adapters = chain(adapters, (IInvalidationOid(obj),)) except TypeError: # No old-style adapter is registered pass transformed = set() for adapter in adapters: o = adapter.transformOid(oid) if isinstance(o, str): transformed.add(o) elif hasattr(o, '__iter__'): # If the transform didn't give back a string, it should have # given back an iterable transformed.update(o) # Get rid of any useless Nones transformed.discard(None) # Get rid of the original oid, if returned. We don't want to use it IF # any transformed oid came back. transformed.discard(oid) target.send(transformed or (oid,))
def available_slots(context): slots = subscribers([context], IMailchimpSlot) return SimpleVocabulary([ SimpleTerm(value=str(li.name), title=li.name) for li in slots \ if queryMultiAdapter((context, context.REQUEST), IMailchimpSlotRenderer, name=li.name)] )
def publishTraverse(self, request, name): view = queryMultiAdapter((self, request), name=name) if view is not None: if ISaveable.providedBy(view): self.saveable = True else: self.saveable = False self.wizard.updateActions() return view for publisher in subscribers((self, request), IPublisherPlugin): try: view = publisher.publishTraverse(request, name) if ISaveable.providedBy(view): self.saveable = True else: self.saveable = False self.wizard.updateActions() return view except NotFound: pass raise NotFound(self, name, request)
def __call__(self, validate_all=False): if HAS_PLONE_6: # Call the default DX content deserializer super().__call__(self) data = json_body(self.request) if "layout" in data: layout = data["layout"] self.context.setLayout(layout) # Volto Blocks on the Plone Site root faker for Plone 5 if not HAS_PLONE_6: # OrderingMixin (needed for correct ordering for Plone < 6) if "ordering" in data and "subset_ids" not in data["ordering"]: data["ordering"]["subset_ids"] = self.context.contentIds() self.handle_ordering(data) if "blocks" in data: value = data["blocks"] for id, block_value in value.items(): block_type = block_value.get("@type", "") handlers = [] for h in subscribers( (self.context, self.request), IBlockFieldDeserializationTransformer, ): if h.block_type == block_type or h.block_type is None: handlers.append(h) for handler in sorted(handlers, key=lambda h: h.order): block_value = handler(block_value) value[id] = block_value if not getattr(self.context, "blocks", False): self.context.manage_addProperty("blocks", json.dumps(value), "string") # noqa else: self.context.manage_changeProperties( blocks=json.dumps(value)) # noqa if "blocks_layout" in data: if not getattr(self.context, "blocks_layout", False): self.context.manage_addProperty("blocks_layout", json.dumps( data["blocks_layout"]), "string") # noqa else: self.context.manage_changeProperties( blocks_layout=json.dumps( data["blocks_layout"])) # noqa if "title" in data: self.context.setTitle(data["title"]) if "description" in data: self.context.manage_changeProperties( description=data["description"]) # noqa return self.context
def apply_handlers(self, item): handlers = [ x for x in subscribers((self.portal, self.request), IPortalTypeMapping) ] for handler in sorted(handlers, key=lambda h: h.order): item = handler(item=item, typekey="_type") return item
def is_private(ob): """ Do any registered private object adapters define this object as private? """ for adapted in subscribers([ob], IPrivateObjectAdapter): if adapted.is_private(): return True return False
def logger_reporter_for_secret_sniffers(event): for sniffer in component.subscribers((event.object, ), mellon.ISecretSniffer): for secret in sniffer: wht_lstd = False for wht_lst in component.subscribers((secret, ), mellon.IWhitelist): for wht_lst_info in wht_lst: logger.info( u"skipping white-listed secret: {} because {}".format( secret, wht_lst_info)) wht_lstd = True if not wht_lstd: logging.warn(\ u"Found secret in file snippet. Secret information: [{}]. Snippet information: [{}]. File information: [{}]."\ .format(secret, event.object.__name__, event.object.__parent__))
def queryMultiSubscriptions(components, interface): """Query for subscriptions on the `components` providing `interface`. :parameter components: tuple of components to lookup the subscription for. :parameter interface: interface that the subscriptions should provide. :return: a list of subscriptions. """ return component.subscribers(components, interface)
def getExportersForSupportedFileFormat(self, file_format): """See `ITranslationExporter`.""" exporters_available = [] for exporter in subscribers([self], ITranslationFormatExporter): if file_format in exporter.supported_source_formats: exporters_available.append(exporter) return exporters_available
def __call__(self): metrics = collections.defaultdict(lambda: {}) for subscriber in component.subscribers((self.context.dmd,), interfaces.ISystemMetric): try: metrics[subscriber.category].update(subscriber.metrics()) except Exception as ex: _LOG.warn("An error occurred gathering performance stats: %s" % ex) self.request.response.write(json.dumps(metrics))
def dispatchToOpaqueItems(ob, event): """Dispatch an event to opaque sub-items of a given object. """ for opaque in ob.opaqueValues(): s = getattr(opaque, '_p_changed', 0) for ignored in subscribers((opaque, event), None): pass # They do work in the adapter fetch if s is None: opaque._p_deactivate()
def __call__(self): self.request.response.content_type = 'application/javascript' mapping = dict() for mapper in subscribers((self.context, ), IClassPathMapping): mapping[mapper.namespace] = IBaseUrl(self.request).url(mapper.path) out = json.dumps(mapping, indent=' ' * 4) self.request.response.write(CLASS_PATH_MAPPER % out) self.request.response.content_type = 'application/javascript'
def getExporterProducingTargetFileFormat(self, file_format): """See `ITranslationExporter`.""" for exporter in subscribers([self], ITranslationFormatExporter): if (exporter.format == file_format or (file_format == TranslationFileFormat.XPI and exporter.format == TranslationFileFormat.XPIPO)): # XPIPO is a special case for XPI exports. return exporter return None
def isVM(self): if self._isVM is None: self._isVM = False for deviceType in subscribers((self._device,), IVirtualDeviceType): vmType = deviceType.vmType() if vmType is not None: self._vmType = vmType self._isVm = True break return self._isVM
def providers(self): providers = [] for provider in subscribers([self.context], IExportProvider): if provider.layer: if not provider.layer.providedBy(self.request): continue providers.append(provider) return providers
def messages(self): """Get all messages """ messages = [] for checker in subscribers((self.context,), ISanityChecker): new_messages = checker() if new_messages: messages += new_messages return messages
def __call__(self): self.request.response.content_type = 'application/javascript' mapping = dict() for mapper in subscribers((self.context,), IClassPathMapping): mapping[mapper.namespace] = IBaseUrl(self.request).url(mapper.path) out = json.dumps(mapping, indent=' ' * 4) self.request.response.write(CLASS_PATH_MAPPER % out) self.request.response.content_type = 'application/javascript'
def publishTraverse(self, request, name): # Look at all the traverser plugins, whether they have an answer. for traverser in subscribers((self.context, request), interfaces.ITraverserPlugin): try: return traverser.publishTraverse(request, name) except NotFound: pass raise NotFound(self.context, name, request)
def messages(self): """Get all messages """ messages = [] for checker in subscribers((self.context, ), ISanityChecker): new_messages = checker() if new_messages: messages += new_messages return messages
def scripts_post_migration(self): """ Excecute a series of post migration steps in order """ handlers = [ x for x in subscribers((self.context, self.request), IPostMigrationStep) ] for handler in sorted(handlers, key=lambda h: h.order): handler(transmogrifier=self.transmogrifier)
def _verifyImport(self, obj): adapted = queryAdapter(object(), IAnotherDummyInterface2) self.failUnless(IAnotherDummyInterface2.providedBy(adapted)) self.failUnless(adapted.verify()) adapted = queryAdapter(object(), IAnotherDummyInterface2, name=u'foo') self.failUnless(IAnotherDummyInterface2.providedBy(adapted)) self.failUnless(adapted.verify()) dummy = DummyObject() results = [ adap.verify() for adap in subscribers([dummy], IAnotherDummyInterface2) ] self.assertEquals(results, [True]) dummy = DummyObject() handle(dummy) self.assertEquals(dummy.handled, 1) util = queryUtility(IDummyInterface2, name=u'foo') self.failUnless(IDummyInterface.providedBy(util)) self.failUnless(util.verify()) self.failUnless(util.__parent__ == obj) name = 'Products.GenericSetup.tests.test_components.IDummyInterface2-foo' self.assertEquals(util.__name__, name) self.failUnless(name in obj.objectIds()) util = queryUtility(IDummyInterface) self.failUnless(IDummyInterface.providedBy(util)) self.failUnless(util.verify()) self.failUnless(util.__parent__ == obj) name = 'dummy_utility' self.assertEquals(util.__name__, name) self.failUnless(name in obj.objectIds()) util = queryUtility(IDummyInterface, name='dummy tool name') self.failUnless(IDummyInterface.providedBy(util)) self.failUnless(util.verify()) self.assertEqual(util.meta_type, 'dummy tool') # make sure we can get the tool by normal means tool = getattr(obj.aq_parent, 'dummy_tool') self.assertEqual(tool.meta_type, 'dummy tool') self.assertEquals(repr(aq_base(util)), repr(aq_base(tool))) util = queryUtility(IDummyInterface2, name='dummy tool name2') self.failUnless(IDummyInterface2.providedBy(util)) self.failUnless(util.verify()) self.assertEqual(util.meta_type, 'dummy tool2') # make sure we can get the tool by normal means tool = getattr(obj.aq_parent, 'dummy_tool2') self.assertEqual(tool.meta_type, 'dummy tool2') self.assertEquals(repr(aq_base(util)), repr(aq_base(tool)))
def _verifyImport(self, obj): adapted = queryAdapter(object(), IAnotherDummy2) self.failUnless(IAnotherDummy2.providedBy(adapted)) self.failUnless(adapted.verify()) adapted = queryAdapter(object(), IAnotherDummy2, name=u'foo') self.failUnless(IAnotherDummy2.providedBy(adapted)) self.failUnless(adapted.verify()) dummy = DummyObject() results = [adap.verify() for adap in subscribers([dummy], IAnotherDummy2)] self.assertEquals(results, [True]) dummy = DummyObject() handle(dummy) self.assertEquals(dummy.handled, 1) util = queryUtility(IDummyInterface2, name=u'foo') self.failUnless(IDummyInterface.providedBy(util)) self.failUnless(util.verify()) self.failUnless(util.__parent__ == obj) name = ('Products.GenericSetup.tests.test_components.' 'IDummyInterface2-foo') self.assertEquals(util.__name__, name) self.failUnless(name in obj.objectIds()) util = queryUtility(IDummyInterface) self.failUnless(IDummyInterface.providedBy(util)) self.failUnless(util.verify()) self.failUnless(util.__parent__ == obj) name = 'dummy_utility' self.assertEquals(util.__name__, name) self.failUnless(name in obj.objectIds()) util = queryUtility(IDummyInterface, name='dummy tool name') self.failUnless(IDummyInterface.providedBy(util)) self.failUnless(util.verify()) self.assertEqual(util.meta_type, 'dummy tool') # make sure we can get the tool by normal means tool = getattr(obj.aq_parent, 'dummy_tool') self.assertEqual(tool.meta_type, 'dummy tool') self.assertEquals(repr(aq_base(util)), repr(aq_base(tool))) util = queryUtility(IDummyInterface2, name='dummy tool name2') self.failUnless(IDummyInterface2.providedBy(util)) self.failUnless(util.verify()) self.assertEqual(util.meta_type, 'dummy tool2') # make sure we can get the tool by normal means tool = getattr(obj.aq_parent, 'dummy_tool2') self.assertEqual(tool.meta_type, 'dummy tool2') self.assertEquals(repr(aq_base(util)), repr(aq_base(tool)))
def getCalendars(self): """Get a list of calendars to display.""" providers = subscribers((self.context, self.request), ICalendarProvider) coloured_calendars = [] for provider in providers: coloured_calendars += provider.getCalendars() calendars = [calendar for (calendar, color1, color2) in coloured_calendars] return calendars
def get_listing_view_adapters(self): """Returns subscriber adapters used to modify the listing behavior, sorted from higher to lower priority """ # Allows to override this listing by multiple subscribers without the # need of inheritance. We use subscriber adapters here because we need # different add-ons to be able to modify columns, etc. without # dependencies amongst them. adapters = subscribers((self, self.context), IListingViewAdapter) return sorted(adapters, key=lambda ad: api.to_float( getattr(ad, "priority_order", 1000)))
def __call__(self, CachableSource, CachedItemFactory): item = CachableSource.first() if not item: raise ValueError("expected CachableSource to be able to generate at least 1 item.") for mapper in subscribers((CachableSource,CachedItemFactory,), ICachedItemMapper): logger.debug("testing mapper/cachedItem combination: %s, %s", str(mapper), str(CachedItemFactory)) if mapper.check(item): logger.debug("found valid ICachedItemMapper %s", str(mapper)) return mapper logger.debug("skipping CachedItemMapper %s because item failed mapper validation check", str(mapper)) raise LookupError("unable to find subscribed ICachedItemMapper for given source and factory: %s, %s", str(CachableSource). str(CachedItemFactory))
def validate(self): # Instead of calling P.Archetypes.BaseObject.validate() we have to # provide a custom validation implementation here because some # validators extract the field value from the request. However a JSON # API request does not contain any form values in the request. # Thus we fake a request that extracts form values from the object on # demand. obj = self.context request = ValidationRequest(self.request, obj) errors = {} obj.pre_validate(request, errors) for pre_validator in subscribers((obj, ), IObjectPreValidation): pre_errors = pre_validator(request) if pre_errors is not None: for field_name, error_message in pre_errors.items(): if field_name in errors: errors[field_name] += " %s" % error_message else: errors[field_name] = error_message obj.Schema().validate(instance=obj, REQUEST=None, errors=errors, data=True, metadata=True) obj.post_validate(request, errors) for post_validator in subscribers((obj, ), IObjectPostValidation): post_errors = post_validator(request) if post_errors is not None: for field_name, error_message in post_errors.items(): if field_name in errors: errors[field_name] += " %s" % error_message else: errors[field_name] = error_message return errors
def __get__(self, form, type=None): if form is None: return Fields() cache = form.__dict__.get(self.key, None) if cache is None and IBrowserView.providedBy(form): providers = component.subscribers( (form.context, form), self.interface) providers = sort_components(providers) cache = Fields(*(p.fields for p in providers)) form.__dict__[self.key] = cache return cache
def notifyFieldEvent(event): field = event.field if IFieldRenderEvent.providedBy(event): event.value = getMultiAdapter((field, event), IFieldValue) if event.kwargs.get('raw', False) or getattr(event, 'raw', False): # bail out return handle(event.field, event.instance, event) if IFieldStorageEvent.providedBy(event): for ignore in subscribers((field, event), IFieldValueSetter): pass
def __api_processor(self, valid_dispatch, valid_response, isubscriber): """ Will loop through a valid response objects and will compare it to a registered protocol subscribers :param valid_dispatch: :param valid_response: :param isubscriber: :return: The chosen API or False """ for sub in subscribers([valid_response], isubscriber): self.__logger.debug('Matched request subscribers: {}'.format(sub.__class__.__name__)) try: verifyObject(isubscriber, sub) except DoesNotImplement as e: self.__logger.warning('Incorrect implementation: {}'.format(e)) else: comp = sub.compare() if comp is not False and IJSONResource.providedBy(comp): self.__logger.debug('Signature compare to {}'.format(comp.__class__.__name__)) # trying to resolve API that will deal with these request if len(comp.to_dict().keys()) > 1: # process request without root element return NonRootAPI(comp).check() else: # root element return RootAPI(comp).check() # if there are no one subsciber from IJSONResource self.__logger.warning('The request {} from type {} was not recognized as a structure or an API'.format( valid_response.response, valid_dispatch.message_type )) return False
def validate(self): # Instead of calling P.Archetypes.BaseObject.validate() we have to # provide a custom validation implementation here because some # validators extract the field value from the request. However a JSON # API request does not contain any form values in the request. # Thus we fake a request that extracts form values from the object on # demand. obj = self.context request = ValidationRequest(self.request, obj) errors = {} obj.pre_validate(request, errors) for pre_validator in subscribers((obj,), IObjectPreValidation): pre_errors = pre_validator(request) if pre_errors is not None: for field_name, error_message in pre_errors.items(): if field_name in errors: errors[field_name] += " %s" % error_message else: errors[field_name] = error_message obj.Schema().validate(instance=obj, REQUEST=None, errors=errors, data=True, metadata=True) obj.post_validate(request, errors) for post_validator in subscribers((obj,), IObjectPostValidation): post_errors = post_validator(request) if post_errors is not None: for field_name, error_message in post_errors.items(): if field_name in errors: errors[field_name] += " %s" % error_message else: errors[field_name] = error_message return errors
def _updateSymptoms(self): self._symptoms = [ symptom for symptom in subscribers((self.context,), ISymptom) if symptom.isActive ] for symptom in self._symptoms: self._byTitle[symptom.title] = symptom self._byName[symptom.name] = symptom self._ignored_symptoms = [ symptom for symptom in self._symptoms if symptom.isIgnored ]