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
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 api.is_dexterity_content(obj): # calculate the download url filename = getattr(field, "filename", "") download = "{url}/@@download/{fieldname}/{filename}".format( url=obj.absolute_url(), fieldname=fieldname, filename=filename, ) else: # calculate the download url download = "{url}/download".format(url=obj.absolute_url(), ) return download
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, }
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") print('------------') print(dm) print(content) print(record) # Iterate through record items print('=============') for k, v in record.items(): print('----------') print(k) print(v) try: success = dm.set(k, v, **record) #starting point 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)
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 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
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 except ValueError: logger.debug("Skipping invalid field '%s'" % fieldname) continue out[fieldname] = get_json_value(obj, fieldname, fieldvalue) return out
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