def _getSchema(self):
     """
     Gets the schema for this content object. The schema must provide
     zope.app.content.interfaces.IContentType to be detected.
     """
     
     return queryContentType(self.context)
Example #2
0
def obterCampos(context, term, nivel):

    results = []
    """
	DESCRIÇÃO: 
		Retorna todos os campos em context
		e os campos dos objetos referenciados
		até o nivel de parâmetro.

	ISSUES:  
		Relações estáticas tem campo vazio por definição (modelo base?);
		
		Campos ocultos não podem ser apresentados;

	"""

    schema = queryContentType(context)
    all_fields = getFieldsInOrder(schema)

    fix_term = ''
    if (len(term) > 0):
        fix_term = term + '/'

    for f in all_fields:
        field_name = str(f[0])

        if (field_name.lower().find('oculto') !=
                -1):  # campos de controle ocultos não são apresentados
            continue

        field_type = str(f[1]).lower()
        term = fix_term + field_name

        if len(term) > 0:
            results.append(term)

        try:
            if (nivel > 1):
                rel = ""
                if (field_type.find("relationchoice") != -1):
                    rel = obterAtributo(context, field_name)
                    rel = rel.to_object
                elif (field_type.find("relationlist") != -1):
                    rel = obterAtributo(context, field_name)
                    rel = rel[0].to_object

                if (len(str(rel)) > 0):
                    res = obterCampos(rel, term, nivel - 1)
                    for r in res:
                        results.append(r)
        except Exception, e:
            pass
Example #3
0
 def test_strategicobjective_fields_type(self):
     """Test of fields type."""
     schema = queryContentType(self.os1)
     fields = getFieldsInOrder(schema)
     # field is a tuple : (field_name, field_obj)
     for field in fields:
         try:
             # strategicobjective_fields_class is a dict : {'field_name': field_class}
             self.assertTrue(
                 isinstance(field[1],
                            self.strategicobjective_fields_class[field[0]]))
         except KeyError as err:
             # its ok for fields excluded intentionally
             print('EXCLUDED : {}'.format(err.message))
             if err.message in STRATEGICOBJECTIVE_EXCLUDED_FIELDS:
                 pass
Example #4
0
    def setDexterityObject(self, obj, file_id):
        """ Set the file- or image-field of dexterity-based types

        This works with the types 'Image' and 'File' of plone.app.contenttypes
        and has fallbacks for other implementations of image- and file-types
        with dexterity.
        """
        request = self.context.REQUEST
        field_name = ''
        info = ''
        try:
            # Use the primary field
            info = IPrimaryFieldInfo(obj, None)
        except TypeError:
            # ttw-types without a primary field throw a TypeError on
            # IPrimaryFieldInfo(obj, None)
            pass
        if info:
            field = info.field
            if INamedImageField.providedBy(field) or \
                    INamedFileField.providedBy(field):
                field_name = info.fieldname
        if not field_name:
            # Use the first field in the schema
            obj_schema = queryContentType(obj)
            obj_fields = getFieldsInOrder(obj_schema)
            for field_info in obj_fields:
                field = field_info[1]
                field_schema = getattr(field, 'schema', None)
                if field_schema and field_schema.getName() in [
                    'INamedBlobImage',
                    'INamedImage',
                    'INamedBlobFile',
                    'INamedFile'
                ]:
                    field_name = field_info[0]
                    break
        if not field_name:
            return False
        else:
            # Create file/image
            setattr(obj, field_name, field._type(request['uploadfile'].read(),
                                                 filename=unicode(file_id)))
        return True
Example #5
0
    def setDexterityObject(self, obj, file_id):
        """ Set the file- or image-field of dexterity-based types

        This works with the types 'Image' and 'File' of plone.app.contenttypes
        and has fallbacks for other implementations of image- and file-types
        with dexterity.
        """
        request = self.context.REQUEST
        field_name = ''
        info = ''
        try:
            # Use the primary field
            info = IPrimaryFieldInfo(obj, None)
        except TypeError:
            # ttw-types without a primary field throw a TypeError on
            # IPrimaryFieldInfo(obj, None)
            pass
        if info:
            field = info.field
            if INamedImageField.providedBy(field) or \
                    INamedFileField.providedBy(field):
                field_name = info.fieldname
        if not field_name:
            # Use the first field in the schema
            obj_schema = queryContentType(obj)
            obj_fields = getFieldsInOrder(obj_schema)
            for field_info in obj_fields:
                field = field_info[1]
                field_schema = getattr(field, 'schema', None)
                if field_schema and field_schema.getName() in [
                        'INamedBlobImage', 'INamedImage', 'INamedBlobFile',
                        'INamedFile'
                ]:
                    field_name = field_info[0]
                    break
        if not field_name:
            return False
        else:
            # Create file/image
            setattr(
                obj, field_name,
                field._type(request['uploadfile'].read(),
                            filename=unicode(file_id)))
        return True
Example #6
0
    def setDexterityItem(self, obj, uploadfile):
        """ Set the blob-field of dexterity-based types

        This works with blob-types of plone.app.contenttypes and has
        fallbacks for other implementations of blob-types with dexterity.

        """
        field_name = ''
        info = ''
        try:
            # Use the primary field if it's an blob-field
            info = IPrimaryFieldInfo(obj, None)
        except TypeError:
            # ttw-types without a primary field throw a TypeError on
            # IPrimaryFieldInfo(obj, None)
            pass
        if info:
            field = info.field
            if INamedField.providedBy(field):
                field_name = info.fieldname
        if not field_name:
            # Use the first blob-field in the schema
            obj_schema = queryContentType(obj)
            obj_fields = getFieldsInOrder(obj_schema)
            for field_info in obj_fields:
                field = field_info[1]
                if INamedField.providedBy(field):
                    field_name = field_info[0]
                    break
        if not field_name:
            return False
        else:
            # Create either a NamedBlobImage or a NamedImage
            setattr(obj, field_name, field._type(uploadfile.read(),
                                                 filename=unicode(id)))
        return True
Example #7
0
    def setDexterityItem(self, obj, uploadfile, filename):
        """ Set the blob-field of dexterity-based types

        This works with blob-types of plone.app.contenttypes and has
        fallbacks for other implementations of blob-types with dexterity.

        """
        field_name = ''
        info = ''
        try:
            # Use the primary field if it's an blob-field
            info = IPrimaryFieldInfo(obj, None)
        except TypeError:
            # ttw-types without a primary field throw a TypeError on
            # IPrimaryFieldInfo(obj, None)
            pass
        if info:
            field = info.field
            if INamedField.providedBy(field):
                field_name = info.fieldname
        if not field_name:
            # Use the first blob-field in the schema
            obj_schema = queryContentType(obj)
            obj_fields = getFieldsInOrder(obj_schema)
            for field_info in obj_fields:
                field = field_info[1]
                if INamedField.providedBy(field):
                    field_name = field_info[0]
                    break
        if not field_name:
            return False
        else:
            # Create either a NamedBlobImage or a NamedImage
            setattr(obj, field_name, field._type(uploadfile.read(),
                                                 filename=unicode(filename)))
        return True
def export_as_csv(self):
    """
    Modify keywords of object
    """

    def processEntry(entry):
        """
        some processing to clean up entries
        """
        if not entry:
            return ''

        # normalize to list
        result = []
        if not isinstance(entry, (list, tuple)):
            entry = [entry,]
        for e in entry:
            if e is None:
                e = ''
            elif not isinstance(e, str) and hasattr(e, 'Title'):
                e = e.Title()
            elif isinstance(e, unicode):
                e = e.encode('utf-8')
            elif not isinstance(e, str):
                e = str(e)
            result.append(e)
        return "\n".join(result)

    fields = self.getCustomViewFields()

    vocab = self.listMetaDataFields(False)
    items = self.queryCatalog(b_size=1000)

    # get the fields to grab
    from zope.app.content import queryContentType
    from zope.schema import getFieldsInOrder
    firstobj = items[0].getObject()
    schema = queryContentType(firstobj)
    extrafields = tuple([f[0] for f in getFieldsInOrder(schema)])

    fields += extrafields
    data = [ [ vocab.getValue(field, field) for field in fields ] ]
    for item in items:
        line = [ getattr(item, field, "") for field in fields if field not in extrafields]

        # handle all the other Dexterity object fields.
        # this will be slow but it probably won't be run frequently
        obj = item.getObject()
        # handle RichTextValue fields differently
        for field in extrafields:
            value = getattr(obj, field, "")
            if isinstance(value, RichTextValue):
                line += [value.raw]
            else:
                line += [value]

        # make entries exportable
        line = [processEntry(e) for e in line]
        data.append(line)

    return export_csv(self.getId(), data, self.REQUEST.RESPONSE)