Beispiel #1
0
 def set(self, instance, value, **kw):
     """Set the value of the (proxy) field
     """
     proxy_field = self.get_proxy_field(instance)
     if proxy_field is None:
         return None
     # set the field with the proper field manager of the proxy field
     fieldmanager = IFieldManager(proxy_field)
     return fieldmanager.set(instance, value, **kw)
Beispiel #2
0
    def json_data(self, name):
        """Get a JSON compatible structure for the named attribute
        """

        # fetch the field by name
        field = api.get_field(self.context, name)

        # bail out if we have no field
        if not field:
            return None

        fieldmanager = IFieldManager(field)
        return fieldmanager.json_data(self.context)
Beispiel #3
0
    def get(self, name):
        """Get the value of the field by name
        """

        # fetch the field by name
        field = api.get_field(self.context, name)

        # bail out if we have no field
        if not field:
            return None

        # call the field adapter and set the value
        fieldmanager = IFieldManager(field)
        return fieldmanager.get(self.context)
Beispiel #4
0
    def set(self, name, value, **kw):
        """Set the field to the given value.

        The keyword arguments represent the other field values
        to integrate constraints to other values.
        """

        # fetch the field by name
        field = api.get_field(self.context, name)

        # bail out if we have no field
        if not field:
            return False

        # call the field adapter and set the value
        fieldmanager = IFieldManager(field)
        return fieldmanager.set(self.context, value, **kw)
Beispiel #5
0
def get_file_info(obj, fieldname, default=None):
    """Extract file data from a file field

    :param obj: Content object
    :type obj: ATContentType/DexterityContentType
    :param fieldname: Schema name of the field
    :type fieldname: str/unicode
    :returns: File data mapping
    :rtype: dict
    """

    # extract the file field from the object if omitted
    field = get_field(obj, fieldname)

    # get the value with the fieldmanager
    fm = IFieldManager(field)

    # return None if we have no file data
    if fm.get_size(obj) == 0:
        return None

    out = {
        "content_type": fm.get_content_type(obj),
        "filename": fm.get_filename(obj),
        "download": fm.get_download_url(obj),
    }

    # only return file data only if requested (?filedata=yes)
    if req.get_filedata(False):
        data = fm.get_data(obj)
        out["data"] = data.encode("base64")

    return out
Beispiel #6
0
    def json_data(self, name):
        """Get a JSON compatible structure for the named attribute
        """

        # Check the write permission of the context
        # XXX: This should be done on field level by the field manager adapter
        if not self.can_write():
            raise Unauthorized("You are not allowed to modify this content")

        # fetch the field by name
        field = api.get_field(self.context, name)

        # bail out if we have no field
        if not field:
            return None

        fieldmanager = IFieldManager(field)
        return fieldmanager.json_data(self.context)
Beispiel #7
0
    def get(self, name):
        """Get the value of the field by name
        """

        # Check the read permission of the context
        # XXX: This should be done on field level by the field manager adapter
        if not self.can_write():
            raise Unauthorized("You are not allowed to modify this content")

        # fetch the field by name
        field = api.get_field(self.context, name)

        # bail out if we have no field
        if field is None:
            return None

        # call the field adapter and set the value
        fieldmanager = IFieldManager(field)
        return fieldmanager.get(self.context)
Beispiel #8
0
    def set(self, name, value, **kw):
        """Set the field to the given value.

        The keyword arguments represent the other field values
        to integrate constraints to other values.
        """

        # Check the write permission of the context
        # XXX: This should be done on field level by the field manager adapter
        if not self.can_write():
            raise Unauthorized("You are not allowed to modify this content")

        # fetch the field by name
        field = api.get_field(self.context, name)

        # bail out if we have no field
        if not field:
            return False

        # call the field adapter and set the value
        fieldmanager = IFieldManager(field)
        return fieldmanager.set(self.context, value, **kw)
Beispiel #9
0
    def update_object_with_data(self, obj, data, domain):
        """Update an existing object with data
        """

        # get the storage and UID map
        storage = self.get_storage(domain=domain)
        uidmap = storage["uidmap"]
        # Proxy Fields must be set after its dependency object is already set.
        # Thus, we will store all the ProxyFields and set them in the end
        proxy_fields = []

        for fieldname, field in api.get_fields(obj).items():

            fm = IFieldManager(field)
            value = data.get(fieldname)

            # handle JSON data reference fields
            if isinstance(value, dict) and value.get("uid"):
                # dereference the referenced object
                value = self.dereference_object(value.get("uid"), uidmap)
            elif isinstance(value, (list, tuple)):
                for item in value:
                    # If it is list of json data dict of objects, add local
                    # uid to that dictionary. This local_uid can be used in
                    # Field Managers.
                    if isinstance(item, dict):
                        for k, v in item.iteritems():
                            if 'uid' in k:
                                local_uid = uidmap.get(v)
                                item[k] = local_uid

            # handle file fields
            if field.type in ("file", "image", "blob"):
                if data.get(fieldname) is not None:
                    fileinfo = data.get(fieldname)
                    url = fileinfo.get("download")
                    filename = fileinfo.get("filename")
                    data["filename"] = filename
                    response = requests.get(url)
                    value = response.content

            # Leave the Proxy Fields for later
            if isinstance(fm, ProxyFieldManager):
                proxy_fields.append({
                    'field_name': fieldname,
                    'fm': fm,
                    'value': value
                })
                continue

            logger.info("Setting value={} on field={} of object={}".format(
                repr(value), fieldname, api.get_id(obj)))
            try:
                fm.set(obj, value)
            except:
                logger.error("Could not set field '{}' with value '{}'".format(
                    fieldname, value))

        # All reference fields are set. We can set the proxy fields now.
        for pf in proxy_fields:
            field_name = pf.get("field_name")
            fm = pf.get("fm")
            value = pf.get("value")
            logger.info("Setting value={} on field={} of object={}".format(
                repr(value), field_name, api.get_id(obj)))
            try:
                fm.set(obj, value)
            except:
                logger.error("Could not set field '{}' with value '{}'".format(
                    field_name, value))

        # Set the workflow states
        wf_info = data.get("workflow_info", [])
        for wf_dict in wf_info:
            wf_id = wf_dict.get("workflow")
            review_history = wf_dict.get("review_history")
            self.import_review_history(obj, wf_id, review_history)

        # finally reindex the object
        self.uids_to_reindex.append([api.get_uid(obj), repr(obj)])
Beispiel #10
0
    def _update_object_with_data(self, obj, data):
        """Update an existing object with data
        """
        # Proxy Fields must be set after its dependency object is already set.
        # Thus, we will store all the ProxyFields and set them in the end
        proxy_fields = []

        for fieldname, field in api.get_fields(obj).items():

            if fieldname in self.fields_to_skip:
                continue

            fm = IFieldManager(field)
            value = data.get(fieldname)
            kwargs = {}

            # Computed Fields don't have set methods.
            if isinstance(fm, ComputedFieldManager):
                continue

            # handle JSON data reference fields
            if isinstance(value, dict) and value.get("uid"):
                # dereference the referenced object
                local_uid = self.sh.get_local_uid(value.get("uid"))
                if local_uid:
                    value = api.get_object_by_uid(local_uid)
                else:
                    value = None

            elif isinstance(value, (list, tuple)):
                for item in value:
                    # If it is list of json data dict of objects, add local
                    # uid to that dictionary. This local_uid can be used in
                    # Field Managers.
                    if isinstance(item, dict):
                        for k, v in item.iteritems():
                            if 'uid' in k:
                                local_uid = self.sh.get_local_uid(v)
                                item[k] = local_uid

            # handle file fields
            if field.type in ("file", "image", "blob"):
                if data.get(fieldname) is not None:
                    fileinfo = data.get(fieldname)
                    url = fileinfo.get("download")
                    filename = fileinfo.get("filename")
                    kwargs["filename"] = filename
                    response = self.session.get(url)
                    value = response.content

            # Leave the Proxy Fields for later
            if isinstance(fm, ProxyFieldManager):
                proxy_fields.append({
                    'field_name': fieldname,
                    'fm': fm,
                    'value': value
                })
                continue
            try:
                fm.set(obj, value, **kwargs)
            except:
                logger.debug("Could not set field '{}' with value '{}'".format(
                    fieldname, value))

        # All reference fields are set. We can set the proxy fields now.
        for pf in proxy_fields:
            field_name = pf.get("field_name")
            fm = pf.get("fm")
            value = pf.get("value")
            try:
                fm.set(obj, value)
            except:
                logger.debug("Could not set field '{}' with value '{}'".format(
                    field_name, value))

        # Set the workflow states
        wf_info = data.get("workflow_info", [])
        for wf_dict in wf_info:
            wf_id = wf_dict.get("workflow")
            review_history = wf_dict.get("review_history")
            self._import_review_history(obj, wf_id, review_history)

        # finally reindex the object
        self.uids_to_reindex.append(api.get_uid(obj))