示例#1
0
def update_object_with_data(content, record):
    """ update the content with the values from records
    """
    dm = IDataManager(content, None)
    if dm is None:
        raise APIError(400, "Update on this object is not allowed")
    for k, v in record.items():
        try:
            success = dm.set(k, v)
        except Unauthorized:
            raise APIError(401,
                           "You are not allowed to set the field '%s'" % k)

        if not success:
            logger.info("update_object_with_data::skipping key=%r", k)
            continue

        logger.info("update_object_with_data::field %r updated with value=%r",
                    k, v)

    # do a wf transition
    if record.get("transition", None):
        t = record.get("transition")
        logger.info(">>> Do Transition '%s' for Object %s", t, content.getId())
        do_action_for(content, t)

    # reindex the object
    content.reindexObject()
    return content
示例#2
0
def update_object_with_data(content, record):
    """ update the content with the values from records
    """
    dm = IDataManager(content, None)
    if dm is None:
        raise APIError(400, "Update on this object is not allowed")
    for k, v in record.items():
        try:
            success = dm.set(k, v)
        except Unauthorized:
            raise APIError(401, "You are not allowed to set the field '%s'" % k)

        if not success:
            logger.info("update_object_with_data::skipping key=%r", k)
            continue

        logger.info("update_object_with_data::field %r updated with value=%r", k, v)

    # do a wf transition
    if record.get("transition", None):
        t = record.get("transition")
        logger.info(">>> Do Transition '%s' for Object %s", t, content.getId())
        do_action_for(content, t)

    # reindex the object
    content.reindexObject()
    return content
示例#3
0
def extract_fields(obj, fieldnames, ignore=[]):
    """Extract the given fieldnames from the object

    :param obj: Content object
    :type obj: ATContentType/DexterityContentType
    :param ignore: Schema names to ignore
    :type ignore: list
    :returns: Schema name/value mapping
    :rtype: dict
    """

    # get the proper data manager for the object
    dm = IDataManager(obj)

    # filter out ignored fields
    fieldnames = filter(lambda name: name not in ignore, fieldnames)

    # schema mapping
    out = dict()

    for fieldname in fieldnames:
        try:
            # get the field value with the data manager
            fieldvalue = dm.get(fieldname)
        # https://github.com/collective/plone.jsonapi.routes/issues/52
        # -> skip restricted fields
        except Unauthorized:
            logger.debug("Skipping restricted field '%s'" % fieldname)
            continue
        out[fieldname] = get_json_value(obj, fieldname, fieldvalue)

    return out
示例#4
0
def extract_fields(obj, fieldnames, ignore=[]):
    """Extract the given fieldnames from the object

    :param obj: Content object
    :type obj: ATContentType/DexterityContentType
    :param ignore: Schema names to ignore
    :type ignore: list
    :returns: Schema name/value mapping
    :rtype: dict
    """

    # get the proper data manager for the object
    dm = IDataManager(obj)

    # filter out ignored fields
    fieldnames = filter(lambda name: name not in ignore, fieldnames)

    # schema mapping
    out = dict()

    for fieldname in fieldnames:
        try:
            # get the field value with the data manager
            fieldvalue = dm.get(fieldname)
        # https://github.com/collective/plone.jsonapi.routes/issues/52
        # -> skip restricted fields
        except Unauthorized:
            logger.debug("Skipping restricted field '%s'" % fieldname)
            continue
        out[fieldname] = get_json_value(obj, fieldname, fieldvalue)

    return out
示例#5
0
    def extract_fields(self):
        """Extract the given fieldnames from the object

        :returns: Schema name/value mapping
        :rtype: dict
        """

        # get the proper data manager for the object
        dm = IDataManager(self.context)

        # filter out ignored fields
        fieldnames = filter(lambda name: name not in self.ignore, self.keys)

        # schema mapping
        out = dict()

        for fieldname in fieldnames:
            try:
                # get the field value with the data manager
                fieldvalue = dm.json_data(fieldname)
            # https://github.com/collective/plone.jsonapi.routes/issues/52
            # -> skip restricted fields
            except Unauthorized:
                logger.debug("Skipping restricted field '%s'" % fieldname)
                continue
            except ValueError:
                logger.debug("Skipping invalid field '%s'" % fieldname)
                continue

            out[fieldname] = api.to_json_value(self.context, fieldname, fieldvalue)

        return out
示例#6
0
def update_object_with_data(content, record):
    """Update the content with the record data

    :param content: A single folderish catalog brain or content object
    :type content: ATContentType/DexterityContentType/CatalogBrain
    :param record: The data to update
    :type record: dict
    :returns: The updated content object
    :rtype: object
    """

    # ensure we have a full content object
    content = get_object(content)

    # get the proper data manager
    dm = IDataManager(content)

    if dm is None:
        raise APIError(400, "Update on this object is not allowed")

    # Iterate through record items
    for k, v in record.items():
        try:
            success = dm.set(k, v, **record)
        except Unauthorized:
            raise APIError(401, "Not allowed to set the field '%s'" % k)

        if not success:
            logger.warn("update_object_with_data::skipping key=%r", k)
            continue

        logger.debug("update_object_with_data::field %r updated", k)

    # do a wf transition
    if record.get("transition", None):
        t = record.get("transition")
        logger.debug(">>> Do Transition '%s' for Object %s", t,
                     content.getId())
        do_action_for(content, t)

    # do a sharing update
    if record.get("sharing", None):
        s = record.get("sharing")
        logger.debug(">>> Update sharing to %r for Object %s", s,
                     content.getId())
        update_sharing_for(content, s)

    # reindex the object
    content.reindexObject()
    return content
示例#7
0
def update_object_with_data(content, record):
    """Update the content with the record data

    :param content: A single folderish catalog brain or content object
    :type content: ATContentType/DexterityContentType/CatalogBrain
    :param record: The data to update
    :type record: dict
    :returns: The updated content object
    :rtype: object
    """

    # ensure we have a full content object
    content = get_object(content)

    # get the proper data manager
    dm = IDataManager(content)

    if dm is None:
        raise APIError(400, "Update on this object is not allowed")

    # Iterate through record items
    for k, v in record.items():
        try:
            success = dm.set(k, v, **record)
        except Unauthorized:
            raise APIError(401, "Not allowed to set the field '%s'" % k)

        if not success:
            logger.warn("update_object_with_data::skipping key=%r", k)
            continue

        logger.debug("update_object_with_data::field %r updated", k)

    # do a wf transition
    if record.get("transition", None):
        t = record.get("transition")
        logger.debug(">>> Do Transition '%s' for Object %s", t, content.getId())
        do_action_for(content, t)

    # do a sharing update
    if record.get("sharing", None):
        s = record.get("sharing")
        logger.debug(">>> Update sharing to %r for Object %s", s, content.getId())
        update_sharing_for(content, s)

    # reindex the object
    content.reindexObject()
    return content
示例#8
0
def get_download_url(obj, fieldname, field=_marker, default=None):
    """Calculate the download url

    :param obj: Content object
    :type obj: ATContentType/DexterityContentType
    :param fieldname: Schema name of the field
    :type fieldname: str/unicode
    :param field: The file field
    :type field: object
    :returns: The file download url
    :rtype: str
    """

    # extract the file field from the object if omitted
    if field is _marker:
        field = IDataManager(obj).get(fieldname)

    # check if we have a file field
    if not is_file_field(field):
        return default

    download = None
    if is_dexterity_content(obj):
        # calculate the download url
        filename = getattr(field, "filename", "")
        download = "{}/@@download/{}/{}".format(obj.absolute_url(), fieldname,
                                                filename)
    else:
        # calculate the download url
        download = "{}/download".format(obj.absolute_url())
    return download
示例#9
0
def get_file_info(obj, fieldname, field=_marker, 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
    :param field: Blob field
    :type field: plone.app.blob.field.BlobWrapper
    :returns: File data mapping
    :rtype: dict
    """

    # extract the file field from the object if omitted
    if field is _marker:
        field = IDataManager(obj).get(fieldname)

    # check if we have a file field
    if not is_file_field(field):
        return default

    # extract file field attributes
    data = field.data.encode("base64")
    content_type = get_content_type(field)
    filename = getattr(field, "filename", "")
    download = get_download_url(obj, fieldname, field)

    return {
        "data": data,
        "size": len(field.data),
        "content_type": content_type,
        "filename": filename,
        "download": download,
    }
示例#10
0
def update_object_with_data(content, record):
    """Update the content with the record data

    :param content: A single folderish catalog brain or content object
    :type content: ATContentType/DexterityContentType/CatalogBrain
    :param record: The data to update
    :type record: dict
    :returns: The updated content object
    :rtype: object
    :raises:
        APIError,
        :class:`~plone.jsonapi.routes.exceptions.APIError`
    """

    # ensure we have a full content object
    content = get_object(content)

    # get the proper data manager
    dm = IDataManager(content)

    if dm is None:
        fail(400, "Update for this object is not allowed")

    # https://github.com/collective/plone.jsonapi.routes/issues/77
    # filter out bogus keywords
    # XXX Maybe we should pass only values where we have identical field names?
    field_kwargs = u.omit(record, "file")

    # Iterate through record items
    for k, v in record.items():
        try:
            success = dm.set(k, v, **field_kwargs)
        except Unauthorized:
            fail(401, "Not allowed to set the field '%s'" % k)
        except ValueError, exc:
            fail(400, str(exc))

        if not success:
            logger.warn("update_object_with_data::skipping key=%r", k)
            continue

        logger.debug("update_object_with_data::field %r updated", k)
示例#11
0
def get_json_value(obj, fieldname, value=_marker, default=None):
    """JSON save value encoding

    :param obj: Content object
    :type obj: ATContentType/DexterityContentType
    :param fieldname: Schema name of the field
    :type fieldname: str/unicode
    :param value: The field value
    :type value: depends on the field type
    :returns: JSON encoded field value
    :rtype: field dependent
    """

    # returned from catalog brain metadata
    if value is Missing.Value:
        return default

    # check if the value is a file field
    if is_file_field(value):

        # Issue https://github.com/collective/plone.jsonapi.routes/issues/54
        # -> return file data only if requested

        if req.get_filedata(False):
            return get_file_info(obj, fieldname, value)

        # return the donwload url as the default file field value
        value = get_download_url(obj, fieldname, value)

    # handle objects from reference fields
    if isinstance(value, ImplicitAcquisitionWrapper):
        return api.get_url_info(value)

    # extract the value from the object if omitted
    if value is _marker:
        value = IDataManager(obj).get(fieldname)

    # check if we have a date
    if is_date(value):
        return get_iso_date(value)

    # handle richtext values
    if is_richtext_value(value):
        value = value.output

    # check if the value is callable
    if callable(value):
        value = value()

    # check if the value is JSON serializable
    if not is_json_serializable(value):
        return default

    return value
示例#12
0
def to_json_value(obj, fieldname, value=_marker, default=None):
    """JSON save value encoding

    :param obj: Content object
    :type obj: ATContentType/DexterityContentType
    :param fieldname: Schema name of the field
    :type fieldname: str/unicode
    :param value: The field value
    :type value: depends on the field type
    :returns: JSON encoded field value
    :rtype: field dependent
    """

    # This function bridges the value of the field to a probably more complex
    # JSON structure to return to the client.

    # extract the value from the object if omitted
    if value is _marker:
        value = IDataManager(obj).json_data(fieldname)

    # convert objects
    if isinstance(value, ImplicitAcquisitionWrapper):
        return get_url_info(value)

    # convert dates
    if is_date(value):
        return to_iso_date(value)

    # check if the value is callable
    if callable(value):
        value = value()

    # check if the value is JSON serializable
    if not is_json_serializable(value):
        logger.warn("Output {} is not JSON serializable".format(repr(value)))
        return default

    return value
示例#13
0
        raise APIError(401, "You are not allowed to create this content")


def update_object_with_data(content, record):
    """ update the content with the values from records
    """
    try:
        if not ploneapi.user.has_permission(
            'Modify portal content',
            user=ploneapi.user.get_current(),
            obj=content
        ):
            raise APIError(401, "You are not allowed to modify content")
    except Exception, e:
        raise APIError(401, "You are not allowed to modify content")
    dm = IDataManager(content, None)
    if dm is None:
        raise APIError(400, "Update on this object is not allowed")
    
    changed = []
    for k, v in record.items():
        try:
            success = dm.set(k, v)
        except Unauthorized:
            raise APIError(401, "You are not allowed to set the field '%s'" % k)

        if not success:
            logger.info("update_object_with_data::skipping key=%r", k)
            continue

        logger.info("update_object_with_data::field %r updated with value=%r", k, v)
 def test_is_file_field(self):
     obj = self.doc
     dm = IDataManager(obj)
     field = dm.get_field("file")
     self.assertTrue(dm.is_file_field(field))