def __setattr__(self, name, value): if name in self.__schema__: reg = self.__registry__ field = self.__schema__.get(name) if IObject.providedBy(field): iface = field.schema collection = reg.collectionOfInterface( iface, check=False, factory=ComplexRecordsProxy) collection[name] = value elif ICollection.providedBy(field) and \ IObject.providedBy(field.value_type): iface = field.value_type.schema # All tuple items are stored as records under # the coll_prefix prefix: coll_prefix = iface.__identifier__ + '.' + name collection = reg.collectionOfInterface( iface, check=False, prefix=coll_prefix, factory=ComplexRecordsProxy) # Clear collection before adding/updating in case of deletes. collection.clear() for idx, val in enumerate(value): # val is our obj created by the z3cform factory collection['r' + str(idx)] = val else: full_name = self.__prefix__ + name if full_name not in reg: raise AttributeError(name) reg[full_name] = value else: self.__dict__[name] = value
def __getattr__(self, name): reg = self.__registry__ if name not in self.__schema__: raise AttributeError(name) field = self.__schema__.get(name) if IObject.providedBy(field): iface = field.schema collection = reg.collectionOfInterface( iface, check=False, factory=ComplexRecordsProxy) if collection.has_key(name): value = collection[name] else: value = _marker elif ICollection.providedBy(field) and \ IObject.providedBy(field.value_type): iface = field.value_type.schema coll_prefix = iface.__identifier__ + '.' + name collection = reg.collectionOfInterface( iface, check=False, prefix=coll_prefix, factory=ComplexRecordsProxy) value = collection.values() if not value: value = _marker else: value = reg.get(self.__prefix__ + name, _marker) if value is _marker: value = self.__schema__[name].missing_value return value
def changedField(field, value, context=None): """Figure if a field's value changed Comparing the value of the context attribute and the given value""" if context is None: context = field.context if context is None: # IObjectWidget madness return True if IObject.providedBy(field): return True # Get the datamanager and get the original value dm = getMultiAdapter( (context, field), IDataManager) # now figure value chaged status # Or we can not get the original value, in which case we can not check # Or it is an Object, in case we'll never know try: test = dm.query() != value if test: return True except TypeError: return True if not dm.canAccess(): return True return False
def getWidget(self, idx): """Create the object widget. This is used to avoid looking up the widget. """ valueType = self.field.value_type if IObject.providedBy(valueType): widget = DataGridFieldObjectFactory(valueType, self.request) if idx in ['TT', 'AA']: widget.setErrors = False else: widget.setErrors = True else: widget = zope.component.getMultiAdapter((valueType, self.request), interfaces.IFieldWidget) self.setName(widget, idx) widget.__parent__ = self widget.mode = self.mode widget.klass = 'datagridwidget-row' #set widget.form (objectwidget needs this) if interfaces.IFormAware.providedBy(self): widget.form = self.form zope.interface.alsoProvides( widget, interfaces.IFormAware) widget.update() return widget
def build_adaptee(field, expand_collection=True): '''Build an adaptee vector for a field instance. This vector is to be used while trying to adapt on fields (for serialization, formatting, widgets etc.). ''' # Load (if not already) the object-factory lookup function. # Note it must be lazily loaded, as is not available at module's load time. from ckanext.publicamundi.lib.metadata import factory_for # Build adaptee vector adaptee = [field] if not expand_collection: return adaptee y = field while IContainerField.providedBy(y): adaptee.append(y.value_type) y = y.value_type if not (y is field) and IObjectField.providedBy(y): # Need a multiadapter for a (probably nested) container of objects: # replace field (instance of ObjectField) with a dummy object adaptee[-1] = factory_for(y.schema)() return adaptee
def __getitem__(self, key): field = self.schema[key] if IContainer.providedBy(field): return VirtualList(self, key, self.context, field.value_type) elif IObject.providedBy(field): return VirtualSection(self, key, self.context, field.schema) raise KeyError(key)
def import_node_for_field(self, field, child): value = None # If we have a collection, we need to look at the value_type. # We look for <element>value</element> child nodes and get the # value from there if ICollection.providedBy(field): value_type = field.value_type value = [] for element in child.childNodes: if element.nodeName != 'element': continue value.append(self.import_node_for_field(value_type, element)) elif IObject.providedBy(field): value = {} for element in child.childNodes: if element.nodeName != 'property': continue property_key = self.extract_text(element.attributes['name']) property_value = self.import_node_for_field(field.schema[property_key], element) value[property_key] = property_value elif IChoice.providedBy(field): # Choice fields can be optional, so treat an empty contents as None value = self.extract_text(child) if not value: value = None else: value = self.from_unicode(field, value) else: # Otherwise, just get the value of the <property /> node value = self.extract_text(child) if not (field.getName() == 'root' and value in ['', '/']): value = self.from_unicode(field, value) value = self.field_typecast(field, value) return value
def __init__(self, parent, name, context, schema): self.__name__ = name self.__parent__ = parent self.context = context if IObject.providedBy(schema): schema = schema.schema self.schema = schema
def test_implements(self): adapter = self._makeOne() assert_that(adapter, validly_provides(interfaces.IRelStorageAdapter)) # pylint:disable=no-value-for-parameter for attr_name, field in interfaces.IRelStorageAdapter.namesAndDescriptions( ): if IObject.providedBy(field): attr_iface = field.schema attr_val = getattr(adapter, attr_name) # Look for functions/methods in its dict and check for __wrapped__ attributes; # these come from perfmetrics @metricmethod and that breaks validation. for k in dir(type(attr_val)): if k not in attr_iface: continue v = getattr(attr_val, k) if callable(v) and hasattr(v, '__wrapped__'): orig = v.__wrapped__ if hasattr(orig, '__get__'): # Must be Python 3, we got the raw unbound function, we need to bind it # and add the self parameter. orig = orig.__get__(type(attr_val), attr_val) try: setattr(attr_val, k, orig) except AttributeError: # Must be slotted. continue assert_that(attr_val, validly_provides(attr_iface))
def is_file_field(self, field): """ checks if field is a file field """ if _.is_string(field): field = self.get_field(field) if self.is_richtext_field(field): return False return IObject.providedBy(field)
def __call__(self, context, field_name, view, request, name=u''): field = get_field(context, field_name) if field is None: raise TypeError, 'invalid field name %s' % field_name field.bind(context) if IObject.providedBy(field): widget = getMultiAdapter((field.get(context), view, request,), name=name) else: widget = getMultiAdapter((field, view, request,), IFieldWidget, name=name) return render_widget(widget)
def createObjectWidget(self, idx): """ """ valueType = self.field.value_type if IObject.providedBy(valueType): widget = BlockDataGridFieldObjectFactory(valueType, self.request) if idx in ['TT', 'AA']: widget.setErrors = False else: widget.setErrors = True else: widget = zope.component.getMultiAdapter((valueType, self.request), interfaces.IFieldWidget) return widget
def createObjectWidget(self, idx): """ Create the widget which handles individual rows. Allow row-widget overriding for more specific use cases. """ valueType = self.field.value_type if IObject.providedBy(valueType): widget = DataGridFieldObjectFactory(valueType, self.request) widget.setErrors = idx not in ['TT', 'AA'] else: widget = zope.component.getMultiAdapter((valueType, self.request), interfaces.IFieldWidget) return widget
def createObjectWidget(self, idx): """ Create the widget which handles individual rows. Allow row-widget overriding for more specific use cases. """ valueType = self.field.value_type if IObject.providedBy(valueType): widget = DataGridFieldObjectFactory(valueType, self.request) if idx in ["TT", "AA"]: widget.setErrors = False else: widget.setErrors = True else: widget = zope.component.getMultiAdapter((valueType, self.request), interfaces.IFieldWidget) return widget
def createObjectWidget(self, idx): """ Create the widget which handles individual rows. Allow row-widget overriding for more specific use cases. """ valueType = self.field.value_type if IObject.providedBy(valueType): widget = DataGridFieldObjectFactory(valueType, self.request) widget.setErrors = idx not in ['TT', 'AA'] else: widget = getMultiAdapter( (valueType, self.request), interfaces.IFieldWidget ) return widget
def export_sub_field(self, doc, parent, field, value): """Turn a zope.schema field into a node and return it """ if value is not None: if ICollection.providedBy(field): for e in value: list_element = doc.createElement('element') self.export_sub_field(doc, list_element, field.value_type, e) parent.appendChild(list_element) elif IObject.providedBy(field): for name, sub_field in field.schema.namesAndDescriptions(): sub_value = value.get(name) list_element = doc.createElement('property') list_element.setAttribute('name', name) self.export_sub_field(doc, list_element, sub_field, sub_value) parent.appendChild(list_element) else: parent.appendChild(doc.createTextNode(unicode(value))) return parent
def changed_field(field, value, context=None): """Figure if a field's value changed Comparing the value of the context attribute and the given value""" if context is None: context = field.context if context is None: # IObjectWidget madness return True if IObject.providedBy(field): return True # Get the datamanager and get the original value dman = get_current_registry().getMultiAdapter((context, field), IDataManager) # now figure value changed status # Or we can not get the original value, in which case we can not check # Or it is an Object, in case we'll never know if (not dman.can_access()) or (dman.query() != value): return True return False
def convertRecord(record, schema): """Converts the QueryRecords from a query result into a dict based on the schema. """ sf_fields = schema.queryTaggedValue('salesforce.fields', {}) sf_relationships = schema.queryTaggedValue('salesforce.relationships', {}) sf_subqueries = schema.queryTaggedValue('salesforce.subqueries', {}) d = {} for fname in schema: field = schema[fname] if fname in sf_fields: # Determine the 'path' to the field value. field_parts = sf_fields[fname].split('.') if fname in sf_relationships.keys(): field_parts = sf_relationships[fname].split('.') + field_parts # Try to get a corresponding value from the record. try: value = valueFromRecord(record, field_parts) except KeyError: continue d[fname] = convertToSchemaValue(field, value) elif fname in sf_relationships: if ICollection.providedBy(field) and IObject.providedBy(field.value_type): subschema = field.value_type.schema subvalues = [] for subrecord in valueFromRecord(record, sf_relationships[fname].split('.')): subvalues.append(convertRecord(subrecord, subschema)) d[fname] = subvalues else: pass elif fname in sf_subqueries: # custom query, we don't know how to find the relevant value on # the record so we just give the converter the whole record and # let it do its thing. # (Things will blow up if there isn't a custom converter!) d[fname] = convertToSchemaValue(field, record) return d
def changedField(field, value, context=None): """Figure if a field's value changed Comparing the value of the context attribute and the given value""" if context is None: context = field.context if context is None: # IObjectWidget madness return True if IObject.providedBy(field): return True # Get the datamanager and get the original value dm = getMultiAdapter((context, field), IDataManager) # now figure value chaged status # Or we can not get the original value, in which case we can not check # Or it is an Object, in case we'll never know try: test = dm.query() != value if test: return True except TypeError: return True if not dm.canAccess(): return True return False
def to_field_value(self, value): """field value is an Object type, that provides field.schema""" if value is NO_VALUE: return self.field.missing_value # try to get the original object, or if there's no chance an empty one obj = self.widget.get_object(value) obj = self.adapted_obj(obj) names = [] registry = self.widget.request.registry for name, field in getFieldsInOrder(self.field.schema): if not field.readonly: try: newval_raw = value[name] except KeyError: continue widget = registry.getMultiAdapter((field, self.widget.request), IFieldWidget) converter = registry.getMultiAdapter((field, widget), IDataConverter) newval = converter.to_field_value(newval_raw) dman = registry.getMultiAdapter((obj, field), IDataManager) oldval = dman.query() if (oldval != newval) or IObject.providedBy(field): dman.set(newval) names.append(name) if names: registry.notify( ObjectModifiedEvent(obj, Attributes(self.field.schema, *names))) return obj
def is_file_field(self, field): """ checks if field is a file field """ return IObject.providedBy(field)
def compound_field(field): return IContainer.providedBy(field) or IObject.providedBy(field)
def queryFromSchema(schema, relationship_name=None, add_prefix=True, sf_object_id=None): """ Given a schema tagged with Salesforce values, generate a query to return all the records for objects of that type. """ sf_object = schema.queryTaggedValue('salesforce.object', None) sf_criteria = schema.queryTaggedValue('salesforce.criteria', None) sf_fields = schema.queryTaggedValue('salesforce.fields', {}) sf_relationships = schema.queryTaggedValue('salesforce.relationships', {}) sf_subqueries = schema.queryTaggedValue('salesforce.subqueries', {}) if sf_object and (sf_fields or sf_relationships or sf_subqueries): if add_prefix: prefix = '%s.' % sf_object else: prefix = '' selects = ['%sId' % prefix] for schema_field_name in schema: if schema_field_name in sf_subqueries: # Has a custom subquery, which takes precedence prevent_dupe(selects, sf_subqueries[schema_field_name]) elif schema_field_name in sf_fields.keys(): # Has both sf:field and sf:relationship if schema_field_name in sf_relationships.keys(): prevent_dupe(selects, '(SELECT %s FROM %s%s)' % ( sf_fields[schema_field_name], prefix, sf_relationships[schema_field_name], )) # Has sf:field but not sf:relationship else: prevent_dupe(selects, '%s%s' % ( prefix, sf_fields[schema_field_name], )) # Has sf:relationship but not sf:field elif schema_field_name in sf_relationships.keys(): field = schema[schema_field_name] # Zope field is an collection whose value_type is IObject: # build subquery based on the object schema if ICollection.providedBy(field) and IObject.providedBy(field.value_type): subquery = queryFromSchema( field.value_type.schema, relationship_name = sf_relationships[schema_field_name], add_prefix = False) prevent_dupe(selects, '(%s)' % subquery) # Otherwise not supported else: raise ValueError('sf:relationship may only be specified without ' 'sf:field if the field is a zope.schema.Object.') # Construct the main query. query = "SELECT %s FROM %s" % ( ', '.join(selects), relationship_name or sf_object ) if sf_criteria: query += " WHERE %s" % sf_criteria if sf_object_id is not None: query += " AND Id='%s'" % sf_object_id elif sf_object_id is not None: query += " WHERE Id='%s'" % sf_object_id logger.debug(query) return query return None