예제 #1
0
    def get_archetypes_fields(self):
        """ If Archetypes is used then dump schema
        """

        try:
            from Products.Archetypes.interfaces import IBaseObject
            if not IBaseObject.providedBy(self.context):
                return
        except:
            return
        if self.is_multilingual() and self.has_tg and len(
                ITranslationManager(
                    self.context).get_translations()) > 1:  # noqa
            translations = ITranslationManager(self.context).get_translations()
            portal_level = len(self.portal.getPhysicalPath())
            trans = {}
            for lang, obj in translations.items():
                trans[lang] = '/' + '/'.join(
                    obj.getPhysicalPath()[portal_level:])
            self['translations'] = trans

        fields = self.context.Schema().fields()
        for field in fields:
            fieldname = unicode(field.__name__)
            type_ = field.__class__.__name__

            fieldnames = [
                'StringField', 'BooleanField', 'LinesField', 'IntegerField',
                'TextField', 'SimpleDataGridField', 'FloatField',
                'FixedPointField', 'TALESString', 'TALESLines', 'ZPTField',
                'DataGridField', 'EmailField', '_StringExtensionField',
                'LeadimageCaptionField', 'ExtensionStandardTagsField',
                'ExtensionHiddenTagsField', 'ExtensionIAmTagsField',
                'ExtensionISearchTagsField', 'CheckboxField'
            ]

            if type_ in fieldnames:
                try:
                    value = field.getRaw(self.context)
                except AttributeError:
                    value = self._get_at_field_value(field)

                if callable(value) is True:
                    value = value()

                if value and type_ in ['StringField', 'TextField']:
                    try:
                        value = self.decode(value)
                    except AttributeError:
                        # maybe an int?
                        value = unicode(value)
                    except Exception, e:
                        raise Exception('problems with %s: %s' %
                                        (self.context.absolute_url(), str(e)))
                elif value and type_ == 'DataGridField':
                    for i, row in enumerate(value):
                        for col_key in row.keys():
                            col_value = row[col_key]
                            if type(col_value) in (unicode, str):
                                value[i][col_key] = self.decode(col_value)

                try:
                    ct = field.getContentType(self.context)
                except AttributeError:
                    ct = ''
                self[unicode(fieldname)] = value
                self[unicode('_content_type_') + fieldname] = ct

            elif type_ in ['DateTimeField']:
                value = self._get_at_field_value(field)
                if value:
                    value = DateTime.DateTime.strftime(value, '%Y-%m-%d %H:%M')
                    # value = str(self._get_at_field_value(field))
                    # value = self._get_at_field_value(field).ISO8601()
                    self[unicode(fieldname)] = value
예제 #2
0
파일: wrapper.py 프로젝트: IMIO/cpskin.core
    def get_archetypes_fields(self):
        """ If Archetypes is used then dump schema
        """

        try:
            from Products.Archetypes.interfaces import IBaseObject
            if not IBaseObject.providedBy(self.context):
                return
        except:
            return
        if self.is_multilingual() and self.has_tg and len(ITranslationManager(self.context).get_translations()) > 1:  # noqa
            translations = ITranslationManager(self.context).get_translations()
            portal_level = len(self.portal.getPhysicalPath())
            trans = {}
            for lang, obj in translations.items():
                trans[lang] = '/'+'/'.join(
                    obj.getPhysicalPath()[portal_level:])
            self['translations'] = trans

        fields = self.context.Schema().fields()
        for field in fields:
            fieldname = unicode(field.__name__)
            type_ = field.__class__.__name__

            fieldnames = [
                'StringField', 'BooleanField', 'LinesField',
                'IntegerField', 'TextField', 'SimpleDataGridField',
                'FloatField', 'FixedPointField', 'TALESString',
                'TALESLines', 'ZPTField', 'DataGridField', 'EmailField',
                '_StringExtensionField', 'LeadimageCaptionField',
                'ExtensionStandardTagsField', 'ExtensionHiddenTagsField',
                'ExtensionIAmTagsField', 'ExtensionISearchTagsField',
                'CheckboxField'
            ]

            if type_ in fieldnames:
                try:
                    value = field.getRaw(self.context)
                except AttributeError:
                    value = self._get_at_field_value(field)

                if callable(value) is True:
                    value = value()

                if value and type_ in ['StringField', 'TextField']:
                    try:
                        value = self.decode(value)
                    except AttributeError:
                        # maybe an int?
                        value = unicode(value)
                    except Exception, e:
                        raise Exception('problems with %s: %s' % (
                            self.context.absolute_url(), str(e))
                        )
                elif value and type_ == 'DataGridField':
                    for i, row in enumerate(value):
                        for col_key in row.keys():
                            col_value = row[col_key]
                            if type(col_value) in (unicode, str):
                                value[i][col_key] = self.decode(col_value)

                try:
                    ct = field.getContentType(self.context)
                except AttributeError:
                    ct = ''
                self[unicode(fieldname)] = value
                self[unicode('_content_type_') + fieldname] = ct

            elif type_ in ['DateTimeField']:
                value = self._get_at_field_value(field)
                if value:
                    value = DateTime.DateTime.strftime(value, '%Y-%m-%d %H:%M')
                    # value = str(self._get_at_field_value(field))
                    # value = self._get_at_field_value(field).ISO8601()
                    self[unicode(fieldname)] = value
예제 #3
0
    def get_dexterity_fields(self):
        """If dexterity is used then extract fields.
        """
        try:
            from plone.dexterity.interfaces import IDexterityContent
            if not self.providedBy(IDexterityContent, self.context):
                return
            from plone.dexterity.utils import iterSchemata
            # from plone.uuid.interfaces import IUUID
            from zope.schema import getFieldsInOrder
            from datetime import date
        except:
            return
        # get translation if thereis
        try:
            if self.is_multilingual() and self.has_tg and len(
                    ITranslationManager(self.context).get_translations()) > 1:
                trans = ITranslationManager(self.context).get_translations()
            else:
                trans = {}
        except:
            trans = {}
        if len(trans) > 1:
            translations = ITranslationManager(self.context).get_translations()
            portal_level = len(self.portal.getPhysicalPath())
            trans = {}
            for lang, obj in translations.items():
                trans[lang] = '/' + '/'.join(
                    obj.getPhysicalPath()[portal_level:])
            self['translations'] = trans
        # get all fields for this obj
        for schemata in iterSchemata(self.context):
            for fieldname, field in getFieldsInOrder(schemata):
                try:
                    value = field.get(schemata(self.context))
                    # value = getattr(context, name).__class__.__name__
                except AttributeError:
                    continue
                if value is field.missing_value:
                    continue

                field_type = field.__class__.__name__

                if field_type in ('RichText', ):
                    # XXX: content_type missing
                    try:
                        value = unicode(value.raw)
                    except:
                        value = u''

                elif field_type in ('NamedImage', 'NamedBlobImage',
                                    'NamedFile', 'NamedBlobFile'):
                    # still to test above with NamedFile & NamedBlobFile
                    fieldname = unicode('_datafield_' + fieldname)

                    if hasattr(value, 'open'):
                        data = value.open().read()
                    else:
                        data = value.data

                    try:
                        max_filesize = int(
                            os.environ.get('JSONIFY_MAX_FILESIZE', 20000000))
                    except ValueError:
                        max_filesize = 20000000

                    if data and len(data) > max_filesize:
                        continue

                    import base64
                    ctype = value.contentType
                    size = value.getSize()
                    dvalue = {
                        'data': base64.b64encode(data),
                        'size': size,
                        'filename': value.filename or '',
                        'content_type': ctype,
                        'encoding': 'base64'
                    }
                    value = dvalue

                elif field_type == 'GeolocationField':
                    # super special plone.formwidget.geolocation case
                    self['latitude'] = getattr(value, 'latitude', 0)
                    self['longitude'] = getattr(value, 'longitude', 0)
                    continue
                elif field_type == 'ContactChoice':
                    pos = getattr(self.context, fieldname, None)
                    if pos:
                        value = unicode(pos.to_path)
                elif isinstance(value, date):
                    value = value.isoformat()

                # elif field_type in ('TextLine',):
                else:
                    BASIC_TYPES = (unicode, int, long, float, bool, type(None),
                                   list, tuple, dict)
                    if type(value) in BASIC_TYPES:
                        pass
                    else:
                        # E.g. DateTime or datetime are nicely representated
                        value = unicode(value)

                self[unicode(fieldname)] = value
예제 #4
0
파일: wrapper.py 프로젝트: IMIO/cpskin.core
    def get_dexterity_fields(self):
        """If dexterity is used then extract fields.
        """
        try:
            from plone.dexterity.interfaces import IDexterityContent
            if not self.providedBy(IDexterityContent, self.context):
                return
            from plone.dexterity.utils import iterSchemata
            # from plone.uuid.interfaces import IUUID
            from zope.schema import getFieldsInOrder
            from datetime import date
        except:
            return
        # get translation if thereis
        try:
            if self.is_multilingual() and self.has_tg and len(ITranslationManager(self.context).get_translations()) > 1:
                trans = ITranslationManager(self.context).get_translations()
            else:
                trans = {}
        except:
            trans = {}
        if len(trans) > 1:
            translations = ITranslationManager(self.context).get_translations()
            portal_level = len(self.portal.getPhysicalPath())
            trans = {}
            for lang, obj in translations.items():
                trans[lang] = '/'+'/'.join(
                    obj.getPhysicalPath()[portal_level:])
            self['translations'] = trans
        # get all fields for this obj
        for schemata in iterSchemata(self.context):
            for fieldname, field in getFieldsInOrder(schemata):
                try:
                    value = field.get(schemata(self.context))
                    # value = getattr(context, name).__class__.__name__
                except AttributeError:
                    continue
                if value is field.missing_value:
                    continue

                field_type = field.__class__.__name__

                if field_type in ('RichText',):
                    # XXX: content_type missing
                    try:
                        value = unicode(value.raw)
                    except:
                        value = u''

                elif field_type in (
                    'NamedImage',
                    'NamedBlobImage',
                    'NamedFile',
                    'NamedBlobFile'
                ):
                    # still to test above with NamedFile & NamedBlobFile
                    fieldname = unicode('_datafield_' + fieldname)

                    if hasattr(value, 'open'):
                        data = value.open().read()
                    else:
                        data = value.data

                    try:
                        max_filesize = int(
                            os.environ.get('JSONIFY_MAX_FILESIZE', 20000000))
                    except ValueError:
                        max_filesize = 20000000

                    if data and len(data) > max_filesize:
                        continue

                    import base64
                    ctype = value.contentType
                    size = value.getSize()
                    dvalue = {
                        'data': base64.b64encode(data),
                        'size': size,
                        'filename': value.filename or '',
                        'content_type': ctype,
                        'encoding': 'base64'
                    }
                    value = dvalue

                elif field_type == 'GeolocationField':
                    # super special plone.formwidget.geolocation case
                    self['latitude'] = getattr(value, 'latitude', 0)
                    self['longitude'] = getattr(value, 'longitude', 0)
                    continue
                elif field_type == 'ContactChoice':
                    pos = getattr(self.context, fieldname, None)
                    if pos:
                        value = unicode(pos.to_path)
                elif isinstance(value, date):
                    value = value.isoformat()

                # elif field_type in ('TextLine',):
                else:
                    BASIC_TYPES = (
                        unicode, int, long, float, bool, type(None),
                        list, tuple, dict
                    )
                    if type(value) in BASIC_TYPES:
                        pass
                    else:
                        # E.g. DateTime or datetime are nicely representated
                        value = unicode(value)

                self[unicode(fieldname)] = value