示例#1
0
    def __call__(self, value):
        if IField.providedBy(self.field.key_type):
            kdeserializer = getMultiAdapter(
                (self.field.key_type, self.context, self.request), IFieldDeserializer
            )
        else:

            def kdeserializer(k):
                return k

        if IField.providedBy(self.field.value_type):
            vdeserializer = getMultiAdapter(
                (self.field.value_type, self.context, self.request), IFieldDeserializer
            )
        else:

            def vdeserializer(v):
                return v

        new_value = {}
        for k, v in value.items():
            new_value[kdeserializer(k)] = vdeserializer(v)

        self.field.validate(new_value)
        return new_value
示例#2
0
 def __init__(self, key_type=None, value_type=None, **kw):
     super(Dict, self).__init__(**kw)
     # whine if key_type or value_type is not a field
     if key_type is not None and not IField.providedBy(key_type):
         raise ValueError("'key_type' must be field instance.")
     if value_type is not None and not IField.providedBy(value_type):
         raise ValueError("'value_type' must be field instance.")
     self.key_type = key_type
     self.value_type = value_type
示例#3
0
 def __init__(self, key_type=None, value_type=None, **kw):
     super(Dict, self).__init__(**kw)
     # whine if key_type or value_type is not a field
     if key_type is not None and not IField.providedBy(key_type):
         raise ValueError("'key_type' must be field instance.")
     if value_type is not None and not IField.providedBy(value_type):
         raise ValueError("'value_type' must be field instance.")
     self.key_type = key_type
     self.value_type = value_type
示例#4
0
    def __call__(self, value):
        kdeserializer = lambda k: k
        vdeserializer = lambda v: v
        if IField.providedBy(self.field.key_type):
            kdeserializer = getMultiAdapter((self.field.key_type, self.context, self.request), IFieldDeserializer)
        if IField.providedBy(self.field.value_type):
            vdeserializer = getMultiAdapter((self.field.value_type, self.context, self.request), IFieldDeserializer)

        new_value = {}
        for k, v in value.items():
            new_value[kdeserializer(k)] = vdeserializer(v)

        self.field.validate(new_value)
        return new_value
示例#5
0
 def __init__(self, value_type=None, unique=False, **kw):
     super(AbstractCollection, self).__init__(**kw)
     # whine if value_type is not a field
     if value_type is not None and not IField.providedBy(value_type):
         raise ValueError("'value_type' must be field instance.")
     self.value_type = value_type
     self.unique = unique
 def __call__(self, context):
     # we take the fti type settings to get the selected connections and table
     if ISQLTypeSchemaContext.providedBy(context):
         context = ISQLTypeSettings(context.fti)
     elif IField.providedBy(context):
         context = ISQLTypeSettings(aq_parent(context.context).fti)
     urls = ISQLAlchemyConnectionStrings(
         component.getUtility(ISiteRoot)).values()
     if not getattr(context, 'sql_connection', None) or not getattr(
             context, 'sql_table', None):
         return SimpleVocabulary([])
     columns = []
     if not ISQLTypeSettings.providedBy(context):
         context = ISQLTypeSettings(context)
     sql_url = context.sql_url
     sql_table = context.sql_table
     engine = create_engine(sql_url)
     insp = reflection.Inspector.from_engine(engine)
     columns = insp.get_columns(sql_table)
     columns.sort(lambda x, y: cmp(x.get('name'), y.get('name')))
     items = [
         SimpleTerm(a.get('name'), a.get('name'),
                    a.get('name') + ' (' + str(a.get('type')) + ')')
         for a in columns
         if a.get('name') and 'TIMESTAMP' in str(a.get('type'))
     ]
     return SimpleVocabulary(items)
示例#7
0
    def __call__(self, context):
        # we take the fti type settings to get the selected connections and table
        if ISQLTypeSchemaContext.providedBy(context):
            context = ISQLTypeSettings(context.fti)
        elif IField.providedBy(context):
            context = ISQLTypeSettings(aq_parent(context.context).fti)
        urls = ISQLAlchemyConnectionStrings(component.getUtility(ISiteRoot)).values()
        if not getattr(context, 'sql_table', None):
            return SimpleVocabulary([])
        items = []
        connection = queryUtility(ISQLConnectionsUtility, name=context.id, default=None)
        if not connection:
            connection = registerConnectionUtilityForFTI(context.context)
        columns = []
        for a in inspect(connection.tableClass).columns:
            if a.name:
                items.append(SimpleTerm(a.name, a.name, a.name+' ('+str(a.type)+')'))
                columns.append(a.name)
        for a in getattr(inspect(connection.tableClass), 'relationships', []):
            if a.key in columns:
                continue
            items.append(SimpleTerm(a.key, a.key, a.key+' (Relation)'))
            for b in inspect(a.table).columns:
                if b.name:
                    items.append(SimpleTerm(a.key+'.'+b.name, a.key+'.'+b.name, a.key+'.'+b.name+' ('+str(b.type)+')'))
                    columns.append(a.key+'.'+b.name)
#            for b in getattr(inspect(connection.tableClass), 'relationships', []):
#                if a.key+'.'+b.key in columns:
#                    continue
#                items.append(SimpleTerm(a.key+'.'+b.key, a.key+'.'+b.key, a.key+'.'+b.key+' (Relation)'))
        items.sort( lambda x, y: cmp(x.value, y.value ) )
        return SimpleVocabulary(items)
示例#8
0
 def __call__(self, context):
     # we take the fti type settings to get the selected connections and table
     if ISQLTypeSchemaContext.providedBy(context):
         context = ISQLTypeSettings(context.fti)
     elif IField.providedBy(context):
         context = ISQLTypeSettings(aq_parent(context.context).fti)
     urls = ISQLAlchemyConnectionStrings(component.getUtility(ISiteRoot)).values()
     if not getattr(context, 'sql_table', None):
         return SimpleVocabulary([])
     columns = []
     sql_connection = context.sql_connection
     sql_table = context.sql_table
     engine = create_engine(sql_connection)
     insp = reflection.Inspector.from_engine(engine)
     base_columns = insp.get_columns(sql_table)
     columns = set()
     for constraint in insp.get_unique_constraints(sql_table):
         if len(constraint.get('column_names')) == 1:
             columns.update(constraint.get('column_names')[0])
     columns = columns.union(set(insp.get_pk_constraint(sql_table).get('constrained_columns')))
     columns = list(columns)
     final = []
     for col in base_columns:
         if col['name'] not in columns:
             continue
         final.append(col.copy())
     final.sort( lambda x, y: cmp(x.get('name'), y.get('name') ) )
     items = [SimpleTerm(a.get('name'), a.get('name'), a.get('name')+' ('+str(a.get('type'))+')') for a in final if a.get('name')]
     return SimpleVocabulary(items)
示例#9
0
 def __call__(self):
     # Binding is necessary for named vocabularies
     if IField.providedBy(self.field):
         self.field = self.field.bind(self.context)
     value = self.get_value()
     value_type = self.field.value_type
     if (
         value is not None
         and IChoice.providedBy(value_type)
         and IVocabularyTokenized.providedBy(value_type.vocabulary)
     ):
         values = []
         for v in value:
             try:
                 term = value_type.vocabulary.getTerm(v)
                 values.append({"token": term.token, "title": term.title})
             except LookupError:
                 log.warning(
                     "Term lookup error: %r %s (%s:%s)"
                     % (
                         v,
                         self.field.title,
                         self.context.portal_type,
                         self.context.absolute_url(1),
                     )
                 )
         value = values
     return json_compatible(value)
示例#10
0
def what_changed(sqlobject_modified_event):
    before = sqlobject_modified_event.object_before_modification
    after = sqlobject_modified_event.object
    fields = sqlobject_modified_event.edited_fields
    changes = {}
    for fieldname in fields:
        # XXX 2011-01-21 gmb bug=705955:
        #     Sometimes, something (webservice, I'm looking at you
        #     here), will create an ObjectModifiedEvent where the
        #     edited_fields list is actually a list of field instances
        #     instead of strings. We special-case that here, but we
        #     shouldn't have to.
        if IField.providedBy(fieldname):
            fieldname = fieldname.getName()
        val_before = getattr(before, fieldname, None)
        val_after = getattr(after, fieldname, None)

        #XXX Bjorn Tillenius 2005-06-09: This shouldn't be necessary.
        # peel off the zope stuff
        if isProxy(val_before):
            val_before = removeSecurityProxy(val_before)
        if isProxy(val_after):
            val_after = removeSecurityProxy(val_after)

        before_string = get_string_representation(val_before)
        after_string = get_string_representation(val_after)

        if before_string != after_string:
            changes[fieldname] = [before_string, after_string]

    return changes
示例#11
0
def what_changed(sqlobject_modified_event):
    before = sqlobject_modified_event.object_before_modification
    after = sqlobject_modified_event.object
    fields = sqlobject_modified_event.edited_fields
    changes = {}
    for fieldname in fields:
        # XXX 2011-01-21 gmb bug=705955:
        #     Sometimes, something (webservice, I'm looking at you
        #     here), will create an ObjectModifiedEvent where the
        #     edited_fields list is actually a list of field instances
        #     instead of strings. We special-case that here, but we
        #     shouldn't have to.
        if IField.providedBy(fieldname):
            fieldname = fieldname.getName()
        val_before = getattr(before, fieldname, None)
        val_after = getattr(after, fieldname, None)

        #XXX Bjorn Tillenius 2005-06-09: This shouldn't be necessary.
        # peel off the zope stuff
        if isProxy(val_before):
            val_before = removeSecurityProxy(val_before)
        if isProxy(val_after):
            val_after = removeSecurityProxy(val_after)

        before_string = get_string_representation(val_before)
        after_string = get_string_representation(val_after)

        if before_string != after_string:
            changes[fieldname] = [before_string, after_string]

    return changes
示例#12
0
 def __init__(self, fields, **kw):
     for ix, field in enumerate(fields):
         if not IField.providedBy(field):
             raise DoesNotImplement(IField)
         field.__name__ = "combination_%02d" % ix
     self.fields = tuple(fields)
     super(Combination, self).__init__(**kw)
示例#13
0
 def __init__(self, fields, **kw):
     for ix, field in enumerate(fields):
         if not IField.providedBy(field):
             raise DoesNotImplement(IField)
         field.__name__ = "combination_%02d" % ix
     self.fields = tuple(fields)
     super(Combination, self).__init__(**kw)
示例#14
0
    def writeAttribute(self, attributeField, field, ignoreDefault=True):
        """Create and return a element that describes the given attribute
        field on the given field
        """

        elementName = attributeField.__name__
        attributeField = attributeField.bind(field)
        value = attributeField.get(field)

        force = (elementName in self.forcedFields)

        if ignoreDefault and value == attributeField.default:
            return None

        # The value points to another field. Recurse.
        if IField.providedBy(value):
            value_fieldType = IFieldNameExtractor(value)()
            handler = queryUtility(IFieldExportImportHandler, name=value_fieldType)
            if handler is None:
                return None
            return handler.write(value, name=None, type=value_fieldType, elementName=elementName)

        # For 'default', 'missing_value' etc, we want to validate against
        # the imported field type itself, not the field type of the attribute
        if elementName in self.fieldTypeAttributes or \
                elementName in self.nonValidatedfieldTypeAttributes:
            attributeField = field

        return valueToElement(attributeField, value, name=elementName, force=force)
示例#15
0
def getValAttributeNames(arg_instance):
    """return a string list of instance attribute names
    """
    classOfInstance = arg_instance.__class__
    #(Pdb) pp classOfInstance.__dict__['address1']
    #<zope.schema.fieldproperty.FieldProperty object at 0xb86d1ec>
    #(Pdb) getattr(classOfInstance, attrName)
    #*** AttributeError: type object 'Address' has no attribute '__annotations__'
    #(Pdb) hasattr(classOfInstance, attrName)
    #False
    retList = []
    classInheritancePath = getClassInheritancePath(classOfInstance,
                                                   endClass=Superclass)
    classInheritancePath.append(classOfInstance)
    print "classInheritancePath: ", classInheritancePath
    askAttributes = []
    allAttributesList = [
        i_class.__dict__.keys() for i_class in classInheritancePath
    ]
    for j_attrList in allAttributesList:
        askAttributes.extend(j_attrList)

    from zope.interface import Attribute
    for attrName, attrValue in arg_instance.__dict__.items():
        if hasattr(classOfInstance, attrName):
            classField = getattr(classOfInstance, attrName)
            #print "%s: (%s): %s" % (attrName, classField, isinstance(classField, Attribute))
            if IField.providedBy(classField) and \
               attrName in askAttributes:
                retList.append(attrName)
    #print "dumdidumm: ", retList
    return retList
示例#16
0
def _validate_fields(schema, value, errors=None):
    if errors is None:
        errors = []
    # Interface can be used as schema property for Object fields that plan to
    # hold values of any type.
    # Because Interface does not include any Attribute, it is obviously not
    # worth looping on its methods and filter them all out.
    if schema is Interface:
        return errors
    # if `value` is part of a cyclic graph, we need to break the cycle to avoid
    # infinite recursion.
    #
    # (use volatile attribute to avoid persistency/conflicts)
    if hasattr(value, '_v_schema_being_validated'):
        return errors
    # Mark the value as being validated.
    value._v_schema_being_validated = True
    # (If we have gotten here, we know that `value` provides an interface
    # other than zope.interface.Interface;
    # iow, we can rely on the fact that it is an instance
    # that supports attribute assignment.)
    try:
        for name in schema.names(all=True):
            if not IMethod.providedBy(schema[name]):
                try:
                    attribute = schema[name]
                    if IField.providedBy(attribute):
                        # validate attributes that are fields
                        attribute.validate(getattr(value, name))
                except ValidationError, error:
                    errors.append(error)
                except AttributeError, error:
                    # property for the given name is not implemented
                    errors.append(SchemaNotFullyImplemented(error))
示例#17
0
 def __init__(self, value_type=None, unique=False, **kw):
     super(AbstractCollection, self).__init__(**kw)
     # whine if value_type is not a field
     if value_type is not None and not IField.providedBy(value_type):
         raise ValueError("'value_type' must be field instance.")
     self.value_type = value_type
     self.unique = unique
示例#18
0
    def __call__(self):
        # Binding is necessary for named vocabularies
        if IField.providedBy(self.field):
            self.field = self.field.bind(self.context)
        value = self.get_value()
        # XXX with elephanvocabulary, "real" vocab is stored on vocabulary.vocab
        vocab = getattr(self.field.vocabulary, "vocab", self.field.vocabulary)
        if value is not None and IVocabularyTokenized.providedBy(vocab):
            try:
                term = self.field.vocabulary.getTerm(value)
            # If not found, get it from the z3c.form that maybe uses a MissingTerms adapter...
            except LookupError:
                try:
                    view = self.context.restrictedTraverse("@@view")
                    view.update()
                    # widget_name is the field name prefixed with behavior if any
                    widget_name = [field for field in get_schema_fields(self.context, prefix=True)
                                   if field[1].__name__ == self.field.__name__][0][0]
                    widget = view.widgets[widget_name]
                    term = widget.terms.getTerm(value)
                except Exception:
                    # at worse use value as title
                    term = SimpleTerm(value, title=value)
            finally:
                value = {"token": term.token, "title": term.title}

        return json_compatible(value)
示例#19
0
def portletManagerDirective(
    _context, name, title, for_=None, description=u'',
    class_=None, schema=None, layer=IDefaultBrowserLayer,
    provides=(), portlettype=IPortlet, **kw):

    # Build a new class
    ManagerClass = PortletManager(
        name, class_, provides, title, description, schema, portlettype, **kw)

    # Set up permission mapping for various accessible attributes
    required = {'__call__': CheckerPublic,
                'browserDefault': CheckerPublic,
                'publishTraverse': CheckerPublic}

    for iname in IPortletManager:
        required[iname] = CheckerPublic

    # security checker
    defineChecker(ManagerClass, Checker(required))

    # security for schema fields
    for iface in (IPortletManagerConfiguration, schema):
        if iface is None:
            continue
        for f_id in iface:
            field = iface[f_id]
            if IField.providedBy(field) and not field.readonly:
                protectSetAttribute(ManagerClass, f_id, 'zojax.ManagePortlets')
            protectName(ManagerClass, f_id, 'zope.Public')

    # register the portlet manager
    adapter(_context, (ManagerClass,),
            IPortletManager, (for_, layer, None), name=name)
示例#20
0
    def export_assignment(self, interface, doc, node):
        for field_name in interface:
            field = interface[field_name]

            if not IField.providedBy(field):
                continue

            child = self.export_field(doc, field)
            node.appendChild(child)
示例#21
0
文件: schema.py 项目: hexsprite/plock
def schema_from_model(model):
    table = model.__table__
    bases = (Interface,)
    attrs = {}
    for i, column in enumerate(table.columns):
        if len(column.foreign_keys) or column.primary_key:
            continue
        field = IField(column.type)
        field.__name__ = str(column.name)
        field.title = unicode(column.name)
        field.required = not column.nullable
        attrs[column.name] = field
        field.order = i
       
    return InterfaceClass(name=model.__table__.name,
                          bases=bases,
                          attrs=attrs,
                          __doc__='Generated from metadata')
示例#22
0
 def __init__(self, field, name=None, klass=None, **args):
     if not IField.providedBy(field):
         raise ValueError("Provided field must implement IField interface...")
     if name is None:
         name = field.__name__
     self.__field = field
     self.__name = name
     self.__klass = klass
     self.__args = args
示例#23
0
    def export_assignment(self, interface, doc, node):
        for field_name in sorted(interface):
            field = interface[field_name]

            if not IField.providedBy(field):
                continue

            child = self.export_field(doc, field)
            node.appendChild(child)
示例#24
0
def Fields(*args, **kw):
    fields = []
    for key, value in kw.items():
        if IField.providedBy(value):
            value.__name__ = key
            fields.append(value)
            del kw[key]
    fields.sort(key=lambda field: field.order)
    return form.Fields(*(args + tuple(fields)), **kw)
示例#25
0
文件: field.py 项目: imegorskaya/py
 def __init__(self, fields, **kw):
     if len(fields) < 2:
         raise ValueError(_("combination must combine two or more fields"))
     for ix, field in enumerate(fields):
         if not IField.providedBy(field):
             raise DoesNotImplement(IField)
         field.__name__ = "combination_%02d" % ix
     self.fields = tuple(fields)
     super(Combination, self).__init__(**kw)
示例#26
0
def Fields(*args, **kw):
    fields = []
    for key, value in kw.items():
        if IField.providedBy(value):
            value.__name__ = key
            fields.append(value)
            del kw[key]
    fields.sort(key=lambda field: field.order)
    return form.Fields(*(args + tuple(fields)), **kw)
示例#27
0
 def __init__(self, fields, use_default_for_not_selected=False, **kw):
     if len(fields) < 2:
         raise ValueError(_("union must combine two or more fields"))
     for ix, field in enumerate(fields):
         if not IField.providedBy(field):
             raise DoesNotImplement(IField)
         field.__name__ = "unioned_%02d" % ix
     self.fields = tuple(fields)
     self.use_default_for_not_selected = use_default_for_not_selected
     super(Union, self).__init__(**kw)
示例#28
0
def sortedFields(schema):
    """Like getFieldsInOrder, but does not include fields from bases
    """
    fields = []
    for name in schema.names(all=False):
        field = schema[name]
        if IField.providedBy(field):
            fields.append((name, field, ))
    fields.sort(key=lambda item: item[1].order)
    return fields
示例#29
0
    def traverse(self, name, ignore):
        field = providedBy(self.context).get(name)
        if field is not None and IField.providedBy(field):
            value = getattr(self.context, name, _marker)
            if value is not _marker:
                bound_field = field.bind(value)
                bound_field.__parent__ = self.context
                return bound_field

        raise NotFound(self.context, name, self.request)
示例#30
0
    def traverse(self, name, ignore):
        field = providedBy(self.context).get(name)
        if field is not None and IField.providedBy(field):
            value = getattr(self.context, name, _marker)
            if value is not _marker:
                bound_field = field.bind(value)
                bound_field.__parent__ = self.context
                return bound_field

        raise NotFound(self.context, name, self.request)
示例#31
0
def getFields(schema):
    """Return a dictionary containing all the Fields in a schema.
    """
    from zope.schema.interfaces import IField
    fields = {}
    for name in schema:
        attr = schema[name]
        if IField.providedBy(attr):
            fields[name] = attr
    return fields
示例#32
0
def sortedFields(schema):
    """Like getFieldsInOrder, but does not include fields from bases
    """
    fields = []
    for name in schema.names(all=False):
        field = schema[name]
        if IField.providedBy(field):
            fields.append((name, field, ))
    fields.sort(key=lambda item: item[1].order)
    return fields
示例#33
0
文件: field.py 项目: imegorskaya/py
 def __init__(self, fields, use_default_for_not_selected=False, **kw):
     if len(fields) < 2:
         raise ValueError(_("union must combine two or more fields"))
     for ix, field in enumerate(fields):
         if not IField.providedBy(field):
             raise DoesNotImplement(IField)
         field.__name__ = "unioned_%02d" % ix
     self.fields = tuple(fields)
     self.use_default_for_not_selected = use_default_for_not_selected
     super(Union, self).__init__(**kw)
示例#34
0
    def __init__(self, value_type=_NotGiven, unique=_NotGiven, **kw):
        super(Collection, self).__init__(**kw)
        # whine if value_type is not a field
        if value_type is not _NotGiven:
            self.value_type = value_type

        if self.value_type is not None and not IField.providedBy(self.value_type):
            raise ValueError("'value_type' must be field instance.")
        if unique is not _NotGiven:
            self.unique = unique
示例#35
0
    def __init__(self, field, factory, name=None):

        if not IField.providedBy(field):
            raise ValueError("Provided field must be an IField object")

        if not IFile.implementedBy(factory):
            raise ValueError("Provided factory is not a valid IFile")

        self.__field = field
        self.__name = name or field.__name__
        self.__factory = factory
示例#36
0
    def __init__(self, field, factory, name=None):

        if not IField.providedBy(field):
            raise ValueError("Provided field must be an IField object")

        if not IFile.implementedBy(factory):
            raise ValueError("Provided factory is not a valid IFile")

        self.__field = field
        self.__name = name or field.__name__
        self.__factory = factory
示例#37
0
    def export_element(self, doc, node):
        if self.descriptor.schema is None:
            return

        for field_name in self.descriptor.schema:
            field = self.descriptor.schema[field_name]

            if not IField.providedBy(field):
                continue

            child = self.export_field(doc, field)
            node.appendChild(child)
 def __call__(self, context):
     # we take the fti type settings to get the selected connections and table
     # on adding, guess the portal_type
     request = getattr(context, 'REQUEST', None)
     request_url = hasattr(request, 'get') and request.get('URL') or ''
     if '++add++' in request_url:
         portal_type = context.REQUEST.get('URL').split('++add++')[1]
         fti = queryUtility(IDexterityFTI, name=portal_type, default=None)
         if fti:
             context = ISQLTypeSettings(fti)
     elif ISQLTypeSchemaContext.providedBy(context):
         context = ISQLTypeSettings(context.fti)
     elif ISQLDexterityItem.providedBy(context):
         fti = queryUtility(IDexterityFTI,
                            name=context.portal_type,
                            default=None)
         if fti:
             context = ISQLTypeSettings(fti)
     elif IField.providedBy(context):
         context = ISQLTypeSettings(aq_parent(context.context).fti)
     urls = ISQLAlchemyConnectionStrings(
         component.getUtility(ISiteRoot)).values()
     if not urls or not getattr(
             context, 'sql_connection', None) or not getattr(
                 context, 'sql_table', None) or not getattr(
                     context, 'sql_id_column', None):
         return SimpleVocabulary([])
     ids = []
     sql_table = context.sql_table
     sql_id_column = context.sql_id_column
     s = text('SELECT ' + sql_id_column + ' FROM ' + sql_table)
     connection = queryUtility(ISQLConnectionsUtility,
                               name=context.id,
                               default=None)
     if not connection:
         connection = registerConnectionUtilityForFTI(context.context)
     try:
         res = connection.conn.execute(s).fetchall()
     except:
         connection.reinit()
         res = connection.conn.execute(s).fetchall()
     items = []
     for a in res:
         title = a[0]
         try:
             title = str(a[0])
         except:
             try:
                 title = str(a[0].encode('utf-8'))
             except:
                 title = str(a[0].decode('utf-8'))
         items.append(SimpleTerm(title, title, title))
     return SimpleVocabulary(items)
示例#39
0
    def export_element(self, doc, node):
        if self.descriptor.schema is None:
            return

        for field_name in self.descriptor.schema:
            field = self.descriptor.schema[field_name]

            if not IField.providedBy(field):
                continue

            child = self.export_field(doc, field)
            node.appendChild(child)
示例#40
0
def schema_indexes(context):
    if IField.providedBy(context):
        _index_types = schema_index_types(context)
        _name = lambda idx, n: '%s_%s' % (idx, n)
        name = context.__name__
        return tuple(_name(idx, name) for idx in _index_types)
    if IInterface.providedBy(context):
        r = []
        for name, field in getFieldsInOrder(context):
            r += list(schema_indexes(field))
        return tuple(r)
    raise ValueError('context must be interface or field')
示例#41
0
def schema_indexes(context):
    if IField.providedBy(context):
        _index_types = schema_index_types(context)
        _name = lambda idx, n: "%s_%s" % (idx, n)
        name = context.__name__
        return tuple(_name(idx, name) for idx in _index_types)
    if IInterface.providedBy(context):
        r = []
        for name, field in getFieldsInOrder(context):
            r += list(schema_indexes(field))
        return tuple(r)
    raise ValueError("context must be interface or field")
    def __call__(self):
        result = {'type': self.field_type}
        for schema in implementedBy(self.field.__class__).flattened():
            self.field_attributes.update(getFields(schema))
        for attribute_name in sorted(self.field_attributes.keys()):
            attribute_field = self.field_attributes[attribute_name]
            if attribute_name in self.filtered_attributes:
                continue

            element_name = attribute_field.__name__
            attribute_field = attribute_field.bind(self.field)
            force = (element_name in self.forced_fields)

            value = attribute_field.get(self.field)

            # For 'default', 'missing_value' etc, we want to validate against
            # the imported field type itself, not the field type of the
            # attribute
            if element_name in self.field_type_attributes or \
                    element_name in self.non_validated_field_type_attributes:
                attribute_field = self.field

            text = None
            if isinstance(value, bytes):
                text = value.decode('utf-8')
            elif isinstance(value, str):
                text = value
            elif IField.providedBy(value):
                serializer = getMultiAdapter((value, self.field, self.request),
                                             ISchemaFieldSerializeToJson)
                text = serializer()
            elif value is not None and (force
                                        or value != self.field.missing_value):
                text = IValueToJson(value)

            # handle i18n
            # if isinstance(value, Message):
            #     child.set(ns('domain', I18N_NAMESPACE), value.domain)
            #     if not value.default:
            #         child.set(ns('translate', I18N_NAMESPACE), '')
            #     else:
            #         child.set(ns('translate', I18N_NAMESPACE), child.text)
            #         child.text = converter.toUnicode(value.default)

            if text:
                if attribute_name == 'value_type':
                    attribute_name = 'items'
                result[attribute_name] = text

        if result['type'] == 'object':
            result['properties'] = self.field.schema
        return result
示例#43
0
 def is_reference_field(self, field):
     """Checks if the field is a reference field type
     """
     if not field:
         return False
     if IField.providedBy(field):
         # TODO: At the moment we do not have a dexterity based reference
         #       field. Implement this when we have an interface for this.
         return False
     field_type = getattr(field, "type", None)
     if field_type is None:
         return False
     return field.type in REF_FIELD_TYPES
示例#44
0
def sortedFields(schema):
    """ Like getFieldsInOrder, but does not include fields from bases

        This is verbatim from plone.supermodel's utils.py but I didn't
        want to create a dependency.
    """
    fields = []
    for name in schema.names(all=False):
        field = schema[name]
        if IField.providedBy(field):
            fields.append((name, field,))
    fields.sort(key=lambda item: item[1].order)
    return fields
示例#45
0
文件: utils.py 项目: CGTIC/Plone_SP
def sortedFields(schema):
    """ Like getFieldsInOrder, but does not include fields from bases

        This is verbatim from plone.supermodel's utils.py but I didn't
        want to create a dependency.
    """
    fields = []
    for name in schema.names(all=False):
        field = schema[name]
        if IField.providedBy(field):
            fields.append((name, field,))
    fields.sort(key=lambda item: item[1].order)
    return fields
 def __protectSetSchema(self, schema, permission_id):
     "Set a permission on a bunch of names."
     _context = self.__context
     for name in schema:
         field = schema[name]
         if IField.providedBy(field) and not field.readonly:
             _context.action(discriminator=('protectSetAttribute',
                                            self.__class, name),
                             callable=protectSetAttribute,
                             args=(self.__class, name, permission_id))
     _context.action(discriminator=None,
                     callable=provideInterface,
                     args=(schema.__module__ + '.' + schema.getName(),
                           schema))
示例#47
0
    def __call__(self, value):
        if not isinstance(value, list):
            value = [value]

        if IField.providedBy(self.field.value_type):
            deserializer = getMultiAdapter((self.field.value_type, self.context, self.request), IFieldDeserializer)

            for i, v in enumerate(value):
                value[i] = deserializer(v)

        value = self.field._type(value)
        self.field.validate(value)

        return value
示例#48
0
 def _marshall_from_json_data(self, value):
     """See `SimpleFieldMarshaller`."""
     template = {}
     for name in self.field.schema.names(all=True):
         field = self.field.schema[name]
         if IField.providedBy(field):
             marshaller = getMultiAdapter(
                 (field, self.request), IFieldMarshaller)
             if marshaller.representation_name in value:
                 template[name] = marshaller.marshall_from_json_data(
                     value[marshaller.representation_name])
             elif field.required:
                 raise RequiredMissing(name)
     return self.field.schema(template)
示例#49
0
 def __call__(self):
     # Binding is necessary for named vocabularies
     if IField.providedBy(self.field):
         self.field = self.field.bind(self.context)
     value = self.get_value()
     value_type = self.field.value_type
     if (value is not None and IChoice.providedBy(value_type)
             and IVocabularyTokenized.providedBy(value_type.vocabulary)):
         values = []
         for v in value:
             term = value_type.vocabulary.getTerm(v)
             values.append({u"token": term.token, u"title": term.title})
         value = self.field._type(values)
     return json_compatible(value)
示例#50
0
    def __init__(self, *args, **kw):
        # Most of this code is copied from zope.formlib.form.Formfields
        # licensed under the ZPL 2.1
        keep_readonly, omit_readonly, defaults = _initkw(**kw)

        fields = []
        fieldsets = ()
        for arg in args:
            if isinstance(arg, InterfaceClass):
                for name, field in getFieldsInOrder(arg):
                    fields.append((name, field))
            elif IField.providedBy(arg):
                name = arg.__name__
                if not name:
                    raise ValueError("Field has no name")
                fields.append((name, arg))
            elif isinstance(arg, FormFieldsets):
                fieldsets = fieldsets + (arg, )
                for form_field in arg:
                    fields.append((form_field.__name__, form_field))
            elif isinstance(arg, FormFields):
                for form_field in arg:
                    fields.append((form_field.__name__, form_field))
            elif isinstance(arg, FormField):
                fields.append((arg.__name__, arg))
            else:
                raise TypeError("Unrecognized argument type", arg)

        self.fieldsets = fieldsets

        seq = []
        byname = {}
        for name, field in fields:
            if isinstance(field, FormField):
                form_field = field
            else:
                if field.readonly:
                    if omit_readonly and (name not in keep_readonly):
                        continue
                form_field = FormField(field, **defaults)
                name = form_field.__name__

            if name in byname:
                raise ValueError("Duplicate name", name)
            seq.append(form_field)
            byname[name] = form_field

        self.__FormFields_seq__ = seq
        self.__FormFields_byname__ = byname
示例#51
0
def _validate_fields(schema, value, errors=None):
    if errors is None:
        errors = []
    for name in schema.names(all=True):
        if not IMethod.providedBy(schema[name]):
            try:
                attribute = schema[name]
                if IField.providedBy(attribute):
                    # validate attributes that are fields
                    attribute.validate(getattr(value, name))
            except ValidationError, error:
                errors.append(error)
            except AttributeError, error:
                # property for the given name is not implemented
                errors.append(SchemaNotFullyImplemented(error))
示例#52
0
文件: form.py 项目: kislovm/findburo
 def __getattr__(self, name):
     schema = self._FormData_schema___
     data = self._FormData_data___
     context = self._FormData_context___
     try:
         field = schema[name]
     except KeyError:
         raise AttributeError(name)
     else:
         value = data.get(name, data)
         if value is data:
             if context is None:
                 raise NoInputData(name)
             # The value is not in the form look it up on the context:
             field = schema[name]
             adapted_context = schema(context)
             if IField.providedBy(field):
                 value = field.get(adapted_context)
             elif (zope.interface.interfaces.IAttribute.providedBy(field)
                   and
                   not zope.interface.interfaces.IMethod.providedBy(field)):
                 # Fallback for non-field schema contents:
                 value = getattr(adapted_context, name)
             else:
                 # Don't know how to extract value
                 raise NoInputData(name)
         if zope.interface.interfaces.IMethod.providedBy(field):
             if not IField.providedBy(field):
                 raise RuntimeError(
                     "Data value is not a schema field", name)
             v = lambda: value
         else:
             v = value
         setattr(self, name, v)
         return v
     raise AttributeError(name)
示例#53
0
文件: form.py 项目: kislovm/findburo
    def __init__(self, *args, **kw):
        keep_readonly, omit_readonly, defaults = _initkw(**kw)

        fields = []
        for arg in args:
            if isinstance(arg, InterfaceClass):
                for name, field in schema.getFieldsInOrder(arg):
                    fields.append((name, field, arg))
            elif IField.providedBy(arg):
                name = arg.__name__
                if not name:
                    raise ValueError(
                            "Field has no name")

                fields.append((name, arg, arg.interface))
            elif isinstance(arg, FormFields):
                for form_field in arg:
                    fields.append(
                        (form_field.__name__,
                         form_field,
                         form_field.interface)
                        )
            elif isinstance(arg, FormField):
                fields.append((arg.__name__, arg, arg.interface))
            else:
                raise TypeError("Unrecognized argument type", arg)


        seq = []
        byname = {}
        for name, field, iface in fields:
            if isinstance(field, FormField):
                form_field = field
            else:
                if field.readonly:
                    if omit_readonly and (name not in keep_readonly):
                        continue
                form_field = FormField(field, interface=iface, **defaults)
                name = form_field.__name__

            if name in byname:
                raise ValueError("Duplicate name", name)
            seq.append(form_field)
            byname[name] = form_field

        self.__FormFields_seq__ = seq
        self.__FormFields_byname__ = byname
示例#54
0
    def cloneField(self, field):

        # XXX: The field may sometimes not have data for reasons known only
        # to Jim.
        try:
            field._p_activate()
        except AttributeError:
            pass

        clone = field.__class__.__new__(field.__class__)
        clone.__dict__.update(field.__dict__)

        for name, attr in field.__dict__.items():
            if IField.providedBy(attr):
                clone.__dict__[name] = self.cloneField(attr)

        return clone
示例#55
0
    def __protectSetSchema(self, schema, permission_id):
        "Set a permission on a bunch of names."
        _context = self._context

        for name in schema:
            field = schema[name]
            if IField.providedBy(field) and not field.readonly:
                _context.action(
                    discriminator = ('zojax:controlpanel:protectSetAttribute',
                                     self._class, name, object()),
                    callable = protectSetAttribute,
                    args = (self._class, name, permission_id))

        _context.action(
            discriminator = None,
            callable = provideInterface,
            args = (schema.__module__+'.'+schema.getName(), schema))