def decode(dump, target=None, target_class=None): data = simplejson.loads(dump) registry = get_current_registry() fields = {} # collect all target's fields by their name if target: for interface in target.__provides__.interfaces(): for name in getFieldNamesInOrder(interface): fields[name] = interface[name] # collect all target_class' fields by their name if target_class: for interface in target_class.__implemented__.interfaces(): for name in getFieldNamesInOrder(interface): fields[name] = interface[name] values = {} for k, v in data.iteritems(): # convert dictionary keys from unicode to str if isinstance(k, unicode): k = k.encode("utf-8") # convert dictionary values to proper field values if k in fields: v = registry.queryMultiAdapter( (fields[k], v), IFieldValue, default=v) values[k] = v return values
def test_renameField(self): s = self.s s.addField(u'alpha', self.alpha) s.renameField(u'alpha', 'beta') self.assertEquals( [u'beta'], getFieldNamesInOrder(s))
def __init__(self, context, request=None): self.context = context self.request = request self.datasets = [] self.datapoints = {} self.schema = IFormDefinition(self.context).schema self.fieldnames = getFieldNamesInOrder(self.schema)
def setUpWidgets(self, ignore_request=False): self.adapters = self.adapters is not None and self.adapters or {} # grab all the adapters and fields from the entire wizard form # sequence (till the current step) adapters = self.wizard.data_manager.adapters fields = self.wizard.data_manager.fields # display widgets for bill/ship address bill_ship_fields = [] form_schemas = component.getUtility(interfaces.IFormSchemas) for i in (form_schemas.getInterface('billing_address'), form_schemas.getInterface('shipping_address')): bill_ship_fields.append( fields.select(*schema.getFieldNamesInOrder(i))) # make copies of custom widgets.. (typically for edit, we want display) bill_ship_fields = sanitize_custom_widgets( reduce(operator.__add__, bill_ship_fields)) self.widgets = form.setUpEditWidgets(bill_ship_fields, self.prefix, self.context, self.request, adapters=adapters, for_display=True, ignore_request=ignore_request)
def search_form(self): uuid = self.data.get('uuid', None) obj = uuidToObject(uuid) if not self.has_listing_search(obj): return available_fields = [] tileType = queryUtility(ITileType, name=self.__name__) conf = self.get_tile_configuration() for name in getFieldNamesInOrder(tileType.schema): if name in conf: field_conf = conf[name] if ('visibility' in field_conf and field_conf['visibility'] == u'off'): # If the field was configured to be invisible, then just # ignore it continue if name.startswith('form_'): available_fields.append(name.split('form_')[1]) search_form = ListingSearchForm(aq_inner(obj), self.request) search_form.fields = search_form.fields.select(*available_fields) search_form.search_url = self.search_url() if HAS_WRAPPED_FORM: alsoProvides(search_form, IWrappedForm) search_form.update() return search_form
def _set_default_configuration(self): defaults = {} tile_type = getUtility(ITileType, name=self.tile.__name__) fields = getFieldNamesInOrder(tile_type.schema) for name, field in getFieldsInOrder(tile_type.schema): order = unicode(fields.index(name)) # default configuration attributes for all fields defaults[name] = {'order': order, 'visibility': u'on'} if name == 'css_class': # css_class, set default defaults[name] = field.default if ITextLine.providedBy(field): # field is TextLine, we should add 'htmltag' defaults[name]['htmltag'] = u'h2' elif INamedBlobImageField.providedBy(field): # field is an image, we should add 'position' and 'imgsize' defaults[name]['position'] = u'left' defaults[name]['imgsize'] = u'mini 200:200' elif IInt.providedBy(field): defaults[name][name] = field.default elif IDatetime.providedBy(field): # field is Datetime, we should add 'format' defaults[name]['format'] = 'datetime' return defaults
def _set_default_configuration(self): defaults = {} tile_type = getUtility(ITileType, name=self.tile.__name__) fields = getFieldNamesInOrder(tile_type.schema) for name, field in getFieldsInOrder(tile_type.schema): order = unicode(fields.index(name)) # default configuration attributes for all fields defaults[name] = {"order": order, "visibility": u"on"} if name == "css_class": # css_class, set default defaults[name] = field.default if ITextLine.providedBy(field): # field is TextLine, we should add 'htmltag' defaults[name]["htmltag"] = u"h2" elif INamedBlobImageField.providedBy(field): # field is an image, we should add 'position' and 'imgsize' defaults[name]["position"] = u"left" defaults[name]["imgsize"] = u"mini 200:200" elif IInt.providedBy(field): defaults[name][name] = field.default elif IDatetime.providedBy(field): # field is Datetime, we should add 'format' defaults[name]["format"] = "datetime" return defaults
class DisplayView(BrowserView): """Simple display-view base class. Subclasses should provide a `schema` attribute defining the schema to be displayed. """ errors = () update_status = '' label = '' # Fall-back field names computes from schema fieldNames = property(lambda self: getFieldNamesInOrder(self.schema)) def __init__(self, context, request): super(DisplayView, self).__init__(context, request) self._setUpWidgets() def _setUpWidgets(self): self.adapted = self.schema(self.context) setUpDisplayWidgets(self, self.schema, source=self.adapted, names=self.fieldNames) def setPrefix(self, prefix): for widget in self.widgets(): widget.setPrefix(prefix) def widgets(self): return [getattr(self, name + '_widget') for name in self.fieldNames]
def format_street_address(item, formatter): address_parts = [] for attribute in getFieldNamesInOrder(IAddress): address_part = getattr(item, attribute, None) if address_part is not None: address_parts.append(address_part) return ", ".join(address_parts)
def _normalize(self): if self.for_ is None: self.for_ = self.schema if self.class_ is None: self.bases = (self.view,) else: self.bases = (self.class_, self.view) if self.template is not None: self.template = os.path.abspath(str(self.template)) if not os.path.isfile(self.template): raise ConfigurationError("No such file", self.template) else: self.template = self.default_template self.names = getFieldNamesInOrder(self.schema) if self.fields: for name in self.fields: if name not in self.names: raise ValueError("Field name is not in schema", name, self.schema) else: self.fields = self.names
def test_removeField(self): s = self.s s.addField(u'alpha', self.alpha) s.removeField(u'alpha') self.assertEquals( [], getFieldNamesInOrder(s))
def __init__(self, context, request=None): ## context should be context of API view, not API view itself self.context = context self.__parent__ = context # may be re-parented by API to view self.request = getRequest() if request is None else request self.definition = IFormDefinition(self.context) self._schema = self.definition.schema self._fieldnames = getFieldNamesInOrder(self._schema)
def test_insertField(self): s = self.s s.addField(u'alpha', self.alpha) beta = Text(title=u"Beta") s.insertField(u'beta', beta, 0) self.assertEquals( [u'beta', u'alpha'], getFieldNamesInOrder(s))
def __init__(self, schema, **kwargs): if IInterface.providedBy(schema): self.identifier = schema.__identifier__ else: self.identifier = str(schema) for name in getFieldNamesInOrder(interfaces.IFlavor): if name in kwargs: setattr(self, name, kwargs.get(name))
def get_unknown_fields(action_data, schema): """Return an error list of unknown fields that are not part of the schema. """ errors = [] known_field_names = getFieldNamesInOrder(schema) for key in action_data: if key not in known_field_names: errors.append((key, UnknownField(key))) return errors
def getFields(context): domain_model = proxy.removeSecurityProxy(context.domain_model) domain_interface = queryModelInterface(domain_model) field_names = schema.getFieldNamesInOrder(domain_interface) for f in field_names: field = domain_interface[f] if isinstance(field, (schema.Choice, schema.Object, schema.List, schema.Tuple, schema.Bytes)): continue yield field
def test_insertFieldCornerCases(self): s = self.s gamma = Text(title=u"Gamma") # it's still possible to insert at beginning s.insertField(u'gamma', gamma, 0) self.assertEquals( [u'gamma'], getFieldNamesInOrder(s)) # should be allowed to insert field at the end s.insertField(u'alpha', self.alpha, 1) self.assertEquals( [u'gamma', u'alpha'], getFieldNamesInOrder(s)) # should be allowed to insert field at the beginning still delta = Text(title=u"Delta") s.insertField(u'delta', delta, 0) self.assertEquals( [u'delta', u'gamma', u'alpha'], getFieldNamesInOrder(s))
def getFields( context ): domain_model = proxy.removeSecurityProxy( context.domain_model ) domain_interface = queryModelInterface( domain_model ) field_names = schema.getFieldNamesInOrder( domain_interface ) for f in field_names: field = domain_interface[ f ] if isinstance( field, ( schema.Choice, schema.Object, schema.List, schema.Tuple, schema.Bytes ) ): continue yield field
def available_fields(self): fields = [] names = [ name for name in getFieldNamesInOrder(IListingSearchTile) if name.startswith('form_') ] for name in names: if self.data.get(name, False): fields.append(name.split('form_')[1]) return fields
def push_data(self): data = self.request.get('json', '[]') data_list = json.loads(data) names = getFieldNamesInOrder(IAnalysisResults) names.remove('uuid') names.remove('sample_no') success_count = 0 for entry in data_list: return_obj = ReturnData() [setattr(return_obj, key, entry[key]) for key in entry] errors = schema.getValidationErrors(IAnalysisResults, return_obj) if errors: msg = [] for error in errors: error_type = error[1].__class__.__name__ field_value = unicode(error[1]) err = u'{0}: {1}; '.format(error_type, field_value) msg.append(err) msg = ''.join(msg) entry.update(dict(_back_success=False, _back_message=msg)) logger.warn(msg) continue else: uuid = entry['uuid'] obj = api.content.uuidToObject(uuid) if obj: [setattr(obj, k, entry[k]) for k in entry if k in names] old_steps = obj.steps new_steps = u'step5' obj.steps = new_steps notify(StepsChangedEvent(obj, old_steps, new_steps)) modified(obj) try: api.content.transition(obj=obj, transition='submit') except (MissingParameterError, InvalidParameterError) as error: msg = 'Warning, {0}'.format(str(error)) logger.warn(error) else: msg = 'Success.' success_count += 1 entry.update(dict(_back_success=True, _back_message=msg)) else: msg = u'Warning, ' \ u'uuid "{0}" not found, skipping.'.format(uuid) entry.update(dict(_back_success=False, _back_message=msg)) logger.warn(msg) failed_count = len(data_list) - success_count msg = u'Analysis of Results: {0} Item Succeeded, ' \ u'{1} Item Failed.'.format(success_count, failed_count) logger.info(msg) return json.dumps(data_list)
def values(obj): registry = get_current_registry() values = {} for interface in obj.__provides__.interfaces(): for name in getFieldNamesInOrder(interface): field = interface[name] bound = field.bind(obj) value = bound.get(obj) values[name] = registry.queryMultiAdapter( (field, value), IJSONValue, default=value) return values
def __init__(cls, name, bases, dct, map_kind=True): """Initializes a class that might implement interfaces""" registry = get_current_registry() implements = getattr(cls, "__implements_advice_data__", None) for interface in (implements and implements[0] or ()): for name in schema.getFieldNamesInOrder(interface): field = interface[name] setattr(cls, name, registry.getAdapter(field, IProperty)) dct.update({name: getattr(cls, name)}) super(SchemaPropertiedClass, cls).__init__(name, bases, dct, map_kind)
def __init__(self, context, request): self.context = context self.request = request self.portal = getSite() self.definition = IFormDefinition(self.context) self.series = context.__parent__ # assumes series <>--- form self.title = '%s: %s' % (self.series.Title().strip(), context.Title()) self.seriesinfo = dict( [(k, v) for k, v in self.series.__dict__.items() if v is not None and k in getFieldNamesInOrder(IFormSeries)] )
def renameField(self, orig_name, target_name): """See zope.app.interfaces.utilities.IMutableSchema""" fields = getFieldNamesInOrder(self) if orig_name not in fields: raise KeyError("Field %s does not exists." % orig_name) if target_name in fields: raise KeyError("Field %s already exists." % target_name) field = self[orig_name] del self[orig_name] field.__name__ = None self[target_name] = field
def __init__(self, context, request): self.context = context self.request = request self.portal = getSite() self.definition = IFormDefinition(self.context) self.series = context.__parent__ # assumes series <>--- form self.title = '%s: %s' % (self.series.Title().strip(), context.Title()) self.seriesinfo = dict([ (k, v) for k, v in self.series.__dict__.items() if v is not None and k in getFieldNamesInOrder(IFormSeries) ])
def getContent(self): data = {'batch_list': []} names = getFieldNamesInOrder(self._list_schema) for obj in self.items: record = {} for name in names: record[name] = getattr(obj, name, None) record['uuid'] = obj.UID() data['batch_list'].append(record) return data
def testSA2ZS(self): iusers = transmute(users) self.assertEqual(tuple(schema.getFieldNamesInOrder(iusers)), ("user_id", "user_name")) fields = dict(schema.getFieldsInOrder(iusers)) # assert types and constraints self.assertTrue(isinstance(fields["user_id"], schema.Int)) self.assertTrue(fields["user_id"].required) self.assertTrue(isinstance(fields["user_name"], schema.TextLine)) self.assertEqual(fields["user_name"].max_length, 40) self.assertEqual(fields["user_name"].default, u"hello world")
def setUpColumns( domain_model ): """ use model descriptor on domain model extract columns for table listings """ columns = [] domain_interface = model.queryModelInterface( domain_model ) if not domain_interface: raise SyntaxError("Model must have domain interface %r"%(domain_model ) ) domain_annotation = model.queryModelDescriptor( domain_interface ) field_column_names = domain_annotation and domain_annotation.listing_columns \ or schema.getFieldNamesInOrder( domain_interface ) # quick hack for now, dates are last in listings remainder = [] for field_name in field_column_names: if not field_name in domain_interface: # we can specify additional columns for tables that are not present in the # the interface, iff they are fully spec'd as columns in the descriptor/annotation if domain_annotation \ and field_name in domain_annotation \ and domain_annotation[ field_name ].listing_column: pass else: #print "bad field, container", field_name, domain_interface.__name__ continue info = domain_annotation and domain_annotation.get( field_name ) or None if info is not None and info.listing_column: columns.append( info.listing_column ) continue field = domain_interface[ field_name ] if isinstance( field, schema.Datetime ): remainder.append( column.GetterColumn( title=field.title or field.__name__, getter=DateGetter( field.query ) ) ) continue columns.append( column.GetterColumn( title= ( field.title or field.__name__ ), getter = Getter( field.query ) ) ) columns.extend( remainder ) return columns
def test_syncSchema_overwrite(self): class ISource(Interface): one = schema.TextLine(title=u"A") two = schema.Int(title=u"B") class IDest(Interface): one = schema.TextLine(title=u"C") three = schema.Int(title=u"D") ISource.setTaggedValue("tag1", "tag one") ISource.setTaggedValue("tag2", "tag two") IDest.setTaggedValue("tag1", "first tag") utils.syncSchema(ISource, IDest, overwrite=True) self.assertEquals(u"A", IDest['one'].title) self.assertEquals(['one', 'two'], getFieldNamesInOrder(ISource)) self.assertEquals(['one', 'two'], getFieldNamesInOrder(IDest)) self.assertEquals("tag one", IDest.getTaggedValue("tag1")) self.assertEquals("tag two", IDest.getTaggedValue("tag2"))
def __getattr__(self, name): """If field, return default for attribute value""" if name.startswith('_v_'): raise AttributeError(name) # no magic tricks with these. schema = self.__class__.schema.__get__(self) # aq property workaround! if name == 'schema': return schema if schema is not None: fieldnames = getFieldNamesInOrder(schema) if name in fieldnames: field = schema.get(name) return field.default raise AttributeError(name)
def testSA2ZS(self): iusers = transmute(users) self.assertEqual(tuple(schema.getFieldNamesInOrder(iusers)), ('user_id', 'user_name')) fields = dict(schema.getFieldsInOrder(iusers)) # assert types and constraints self.assertTrue(isinstance(fields['user_id'], schema.Int)) self.assertTrue(fields['user_id'].required) self.assertTrue(isinstance(fields['user_name'], schema.TextLine)) self.assertEqual(fields['user_name'].max_length, 40) self.assertEqual(fields['user_name'].default, u'hello world')
def test_syncSchema(self): class ISource(Interface): one = schema.TextLine(title=u"A") # order: 0 two = schema.Int(title=u"B") # order: 1 class IDest(Interface): one = schema.TextLine(title=u"C") # order: 0 three = schema.Int(title=u"D") # order: 1 ISource.setTaggedValue("tag1", "tag one") ISource.setTaggedValue("tag2", "tag two") IDest.setTaggedValue("tag1", "first tag") utils.syncSchema(ISource, IDest) self.assertEqual(u"C", IDest['one'].title) self.assertEqual(['one', 'two'], getFieldNamesInOrder(ISource)) self.assertEqual(['two', 'one', 'three'], getFieldNamesInOrder(IDest)) self.assertEqual("first tag", IDest.getTaggedValue("tag1")) self.assertEqual("tag two", IDest.getTaggedValue("tag2"))
def test_syncSchema_overwrite(self): class ISource(Interface): one = schema.TextLine(title=u"A") two = schema.Int(title=u"B") class IDest(Interface): one = schema.TextLine(title=u"C") three = schema.Int(title=u"D") ISource.setTaggedValue("tag1", "tag one") ISource.setTaggedValue("tag2", "tag two") IDest.setTaggedValue("tag1", "first tag") utils.syncSchema(ISource, IDest, overwrite=True) self.assertEqual(u"A", IDest["one"].title) self.assertEqual(["one", "two"], getFieldNamesInOrder(ISource)) self.assertEqual(["one", "two"], getFieldNamesInOrder(IDest)) self.assertEqual("tag one", IDest.getTaggedValue("tag1")) self.assertEqual("tag two", IDest.getTaggedValue("tag2"))
def setUpWidgets(self, ignore_request=False): self.adapters = self.adapters is not None and self.adapters or {} # grab all the adapters and fields from the entire wizard form sequence # (till the current step) adapters = self.wizard.data_manager.adapters fields = self.wizard.data_manager.fields formSchemas = component.getUtility(interfaces.IFormSchemas) # edit widgets for payment info self.widgets = form.setUpEditWidgets( self.form_fields.select( *schema.getFieldNamesInOrder( formSchemas.getInterface('payment') ) ), self.prefix, self.context, self.request, adapters=adapters, ignore_request=ignore_request ) # display widgets for bill/ship address bill_ship_fields = [] for i in (formSchemas.getInterface('billing_address'), formSchemas.getInterface('shipping_address')): bill_ship_fields.append( fields.select( *schema.getFieldNamesInOrder(i) ) ) # make copies of custom widgets.. (typically for edit, we want display) bill_ship_fields = sanitize_custom_widgets( reduce(operator.__add__, bill_ship_fields) ) self.widgets += form.setUpEditWidgets( bill_ship_fields, self.prefix, self.context, self.request, adapters=adapters, for_display=True, ignore_request=ignore_request )
def test_moveField(self): s = self.s s.addField(u'alpha', self.alpha) beta = Text(title=u'Beta') s.addField(u'beta', beta) gamma = Text(title=u'Gamma') s.addField(u'gamma', gamma) s.moveField(u'beta', 3) self.assertEquals( [u'alpha', u'gamma', u'beta'], getFieldNamesInOrder(s)) s.moveField(u'beta', 2) self.assertEquals( [u'alpha', u'gamma', u'beta'], getFieldNamesInOrder(s)) s.moveField(u'beta', 1) self.assertEquals( [u'alpha', u'beta', u'gamma'], getFieldNamesInOrder(s)) s.moveField(u'beta', 0) self.assertEquals( [u'beta', u'alpha', u'gamma'], getFieldNamesInOrder(s))
def attributes(self): context = removeSecurityProxy(self.context) attrs = [{'name': (ns and context.prefixes[ns]+':' or '') + name, 'value': value, 'url': None, 'values': []} for (ns, name), value in context.attrs.items()] names = context.schema.names(True) rootURL = absoluteURL(findDocModule(self), self.request) for attr in attrs: name = (attr['name'] in names) and attr['name'] or attr['name']+'_' field = context.schema.get(name) if isinstance(field, (GlobalObject, GlobalInterface)): attr['url'] = self.objectURL(attr['value'], field, rootURL) elif isinstance(field, Tokens): field = field.value_type values = attr['value'].strip().split() if len(values) == 1: attr['value'] = values[0] attr['url'] = self.objectURL(values[0], field, rootURL) else: for value in values: if isinstance(field, (GlobalObject, GlobalInterface)): url = self.objectURL(value, field, rootURL) else: break attr['values'].append({'value': value, 'url': url}) # Make sure that the attributes are in the same order they are defined # in the schema. fieldNames = getFieldNamesInOrder(context.schema) fieldNames = [name.endswith('_') and name[:-1] or name for name in fieldNames] attrs.sort(lambda x, y: _compareAttrs(x, y, fieldNames)) if not IRootDirective.providedBy(context): return attrs xmlns = [] for uri, prefix in context.prefixes.items(): name = prefix and ':'+prefix or '' xmlns.append({'name': 'xmlns'+name, 'value': uri, 'url': None, 'values': []}) xmlns.sort(lambda x, y: cmp(x['name'], y['name'])) return xmlns + attrs
def test_syncSchema(self): class ISource(Interface): one = schema.TextLine(title=u"A") # order: 0 two = schema.Int(title=u"B") # order: 1 class IDest(Interface): one = schema.TextLine(title=u"C") # order: 0 three = schema.Int(title=u"D") # order: 1 ISource.setTaggedValue("tag1", "tag one") ISource.setTaggedValue("tag2", "tag two") IDest.setTaggedValue("tag1", "first tag") utils.syncSchema(ISource, IDest) self.assertEquals(u"C", IDest['one'].title) self.assertEquals(['one', 'two'], getFieldNamesInOrder(ISource)) self.assertEquals(['two', 'one', 'three'], getFieldNamesInOrder(IDest)) self.assertEquals("first tag", IDest.getTaggedValue("tag1")) self.assertEquals("tag two", IDest.getTaggedValue("tag2"))
def setUpColumns(domain_model): """Use model descriptor on domain model extract columns for table listings """ columns = [] table_schema = bungeni.alchemist.utils.get_derived_table_schema( domain_model) if not table_schema: raise SyntaxError( "Model must have domain interface %r" % (domain_model)) descriptor_model = bungeni.alchemist.utils.get_descriptor(table_schema) field_column_names = \ descriptor_model and descriptor_model.listing_columns \ or schema.getFieldNamesInOrder(table_schema) # quick hack for now, dates are last in listings remainder = [] for field_name in field_column_names: if not field_name in table_schema: # we can specify additional columns for tables that are not present in the # the interface, iff they are fully spec'd as columns in the descriptor/annotation if (descriptor_model and field_name in descriptor_model and descriptor_model[field_name].listing_column): pass else: #print "bad field, container", field_name, table_schema.__name__ continue info = descriptor_model and descriptor_model.get(field_name) or None if info is not None and info.listing_column: columns.append(info.listing_column) continue field = table_schema[field_name] if isinstance(field, schema.Datetime): remainder.append( column.GetterColumn( title=field.title or field.__name__, getter=DateGetter(field.query))) continue columns.append( column.GetterColumn( title=(field.title or field.__name__), getter=Getter(field.query))) columns.extend(remainder) return columns
def getContent(self): data = {'batch_list': []} names = getFieldNamesInOrder(self._list_schema) for obj in self.items: record = {} for name in names: record[name] = getattr(obj, name, None) record['uuid'] = obj.UID() record['review_state'] = translate(_( api.content.get_state(obj).title()), context=api.portal.getRequest()) data['batch_list'].append(record) return data
def _flex_form_hasdata(self, form): groups = self._datagroups(form) # form.data will not contain fieldset records on created but # otherwise unsaved form: _fieldsets = dict([(k, form.data.get(k)) for k in groups.keys()]) # scenario 1: form exists, but no fieldset records (never entered): if not all(_fieldsets.values()): return False # scenario 2: form exists, but fieldset records may or may not be # empty; if empty, return False -- otherwise True. return any( fieldset_nonempty(r, groups.get(k).schema) for k, r in _fieldsets.items() if getFieldNamesInOrder(groups.get(k).schema))
def _flex_form_hasdata(self, form): groups = self._datagroups(form) # form.data will not contain fieldset records on created but # otherwise unsaved form: _fieldsets = dict([(k, form.data.get(k)) for k in groups.keys()]) # scenario 1: form exists, but no fieldset records (never entered): if not all(_fieldsets.values()): return False # scenario 2: form exists, but fieldset records may or may not be # empty; if empty, return False -- otherwise True. return any( fieldset_nonempty(r, groups.get(k).schema) for k, r in _fieldsets.items() if getFieldNamesInOrder(groups.get(k).schema) )
def _get_scss_variables(self, obj): schema = queryMultiAdapter((obj, obj.REQUEST), ICustomDesignVariablesSchema) if not schema: return annotations = IAnnotations(obj, None) if not annotations: return variables = annotations.get(VARIABLES_ANNOTATION_KEY) or {} form_fields = getFields(schema) for field_name in getFieldNamesInOrder(schema): yield (form_fields[field_name].variable_name, variables.get(field_name))
def setUpColumns(domain_model): """Use model descriptor on domain model extract columns for table listings """ columns = [] table_schema = bungeni.alchemist.utils.get_derived_table_schema( domain_model) if not table_schema: raise SyntaxError("Model must have domain interface %r" % (domain_model)) descriptor_model = bungeni.alchemist.utils.get_descriptor(table_schema) field_column_names = \ descriptor_model and descriptor_model.listing_columns \ or schema.getFieldNamesInOrder(table_schema) # quick hack for now, dates are last in listings remainder = [] for field_name in field_column_names: if not field_name in table_schema: # we can specify additional columns for tables that are not present in the # the interface, iff they are fully spec'd as columns in the descriptor/annotation if (descriptor_model and field_name in descriptor_model.fields_by_name and descriptor_model.get(field_name).listing_column): pass else: print "bad field, container", field_name, table_schema.__name__ continue info = descriptor_model and descriptor_model.get(field_name) or None if info is not None and info.listing_column: columns.append(info.listing_column) continue field = table_schema[field_name] if isinstance(field, schema.Datetime): remainder.append( column.GetterColumn(title=field.title or field.__name__, getter=DateGetter(field.query))) continue columns.append( column.GetterColumn(title=(field.title or field.__name__), getter=Getter(field.query))) columns.extend(remainder) return columns
def test_syncSchema_overwrite_no_bases(self): class IBase(Interface): base = schema.TextLine(title=u"Base") class ISource(IBase): one = schema.TextLine(title=u"A") two = schema.Int(title=u"B") class IDest(Interface): one = schema.TextLine(title=u"C") three = schema.Int(title=u"D") utils.syncSchema(ISource, IDest, overwrite=False, sync_bases=False) self.assertEquals((Interface, ), IDest.__bases__) self.assertEquals(['two', 'one', 'three'], getFieldNamesInOrder(IDest))
def __init__(self, context, request, factory, **kw): super(ObjectWidget, self).__init__(context, request) # define view that renders the widget self.view = ObjectWidgetView(self, request) # factory used to create content that this widget (field) # represents self.factory = factory # handle foo_widget specs being passed in self.names = getFieldNamesInOrder(self.context.schema) for k, v in kw.items(): if k.endswith('_widget'): setattr(self, k, v) # set up my subwidgets self._setUpEditWidgets()
def test_syncSchema_overwrite_with_bases(self): class IBase(Interface): base = schema.TextLine(title=u"Base") class IOtherBase(Interface): foo = schema.TextLine(title=u"Foo") class ISource(IBase): one = schema.TextLine(title=u"A") two = schema.Int(title=u"B") class IDest(IOtherBase): one = schema.TextLine(title=u"C") three = schema.Int(title=u"D") utils.syncSchema(ISource, IDest, overwrite=True, sync_bases=True) self.assertEqual((IBase, ), IDest.__bases__) self.assertEqual(['base', 'one', 'two'], getFieldNamesInOrder(IDest))
def update(self, data): """ Update from JSON data or equivalent dict. """ if isinstance(data, basestring): data = json.loads(data) queries = [] fieldnames = getFieldNamesInOrder(self.schema) for query_row in data.get('rows', []): fieldname = query_row.get('fieldname') if fieldname not in fieldnames: continue # ignore possibly removed fields field = self.schema[fieldname] comparator = query_row.get('comparator') value = self.normalize_value( field, query_row.get('value'), ) queries.append(FieldQuery(fieldname, comparator, value)) self.context.reset() # clear queries self.context.operator = data.get('operator', 'AND') r = map(self.context.add, queries) # add all # noqa
def __iter__(self): key = self.options.get('key') for item in self.previous: if self.condition(item): if '_object' in item and key: item[key] = marshall(item['_object']) # For Topics, also marshall required fields for collections if item['_type'] == 'Topic': ob = item['_object'] message = marshall_topic_as_collection(ob) for name in getFieldNamesInOrder(IMockCollection): item[key][name] = message[name] # Because sub-collections are not supported, re-create # the main topic as separate collection... if has_subtopics(ob): id_ = item['_path'].split('/')[-1] while id_ in ob.objectIds(): id_ += '-{0:s}'.format(id_) item['_path'] += '/{0:s}'.format(id_) yield item
def __iter__(self): context = self.transmogrifier.context key = self.options.get('key') for item in self.previous: if item.get('_type') == 'Topic': obj = resolve_object(context, item) item[key] = marshall(obj) # For Topics, also marshall required fields for collections obj = item['_object'] message = marshall_topic_as_collection(obj) for name in getFieldNamesInOrder(IMockCollection): item[key][name] = message[name] # Because sub-collections are not supported, re-create # the main topic as separate collection... if has_subtopics(obj): id_ = item['_path'].split('/')[-1] while id_ in obj.objectIds(): id_ += '-{0:s}'.format(id_) item['_path'] += '/{0:s}'.format(id_) yield item
def testSA2ZS(self): metadata = rdb.DynamicMetaData("principals") users = rdb.Table( 'users', metadata, rdb.Column('user_id', rdb.Integer, rdb.Sequence('user_id_seq', optional=True), primary_key=True), rdb.Column('user_name', rdb.String(40), default=u'hello world')) iusers = transmute(users) self.assertEqual(tuple(schema.getFieldNamesInOrder(iusers)), ('user_id', 'user_name')) fields = dict(schema.getFieldsInOrder(iusers)) # assert types and constraints self.assertTrue(isinstance(fields['user_id'], schema.Int)) self.assertTrue(fields['user_id'].required) self.assertTrue(isinstance(fields['user_name'], schema.TextLine)) self.assertEqual(fields['user_name'].max_length, 40) self.assertEqual(fields['user_name'].default, u'hello world')
class ProjectSnapshot(object): implements(IProjectSnapshot) NAMES = schema.getFieldNamesInOrder(IProjectSnapshot) def __init__(self, **kwargs): # initially empty sets for users, can be intersected later self.all_users = set() self.other_users = set() self.managers = set() self.form_users = set() for k, v in kwargs.items(): if k in self.NAMES: IProjectSnapshot[k].validate(v) setattr(self, k, v) def __setattr__(self, name, value): """Validating setattr for any schema fields""" if name in self.NAMES: IProjectSnapshot[name].validate(value) self.__dict__[name] = value
class EditView(BrowserView): """Simple edit-view base class Subclasses should provide a `schema` attribute defining the schema to be edited. The automatically generated widgets are available by name through the attributes `*_widget`. (E.g. ``view.title_widget for the title widget``) """ errors = () update_status = None label = '' # Fall-back field names computes from schema fieldNames = property(lambda self: getFieldNamesInOrder(self.schema)) # Fall-back template generated_form = ViewPageTemplateFile('edit.pt') def __init__(self, context, request): super(EditView, self).__init__(context, request) self._setUpWidgets() def _setUpWidgets(self): self.adapted = self.schema(self.context) setUpEditWidgets(self, self.schema, source=self.adapted, names=self.fieldNames) def setPrefix(self, prefix): for widget in self.widgets(): widget.setPrefix(prefix) def widgets(self): return [getattr(self, name + '_widget') for name in self.fieldNames] def changed(self): # This method is overridden to execute logic *after* changes # have been made. pass def update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status status = '' content = self.adapted if Update in self.request: changed = False try: changed = applyWidgetsChanges(self, self.schema, target=content, names=self.fieldNames) # We should not generate events when an adapter is used. # That's the adapter's job. if changed and self.context is self.adapted: description = Attributes(self.schema, *self.fieldNames) notify(ObjectModifiedEvent(content, description)) except WidgetsError, errors: self.errors = errors status = _("An error occurred.") transaction.doom() else: setUpEditWidgets(self, self.schema, source=self.adapted, ignoreStickyValues=True, names=self.fieldNames) if changed: self.changed() formatter = self.request.locale.dates.getFormatter( 'dateTime', 'medium') status = _("Updated on ${date_time}", mapping={ 'date_time': formatter.format(datetime.utcnow()) }) self.update_status = status return status