Python jsonpatch.apply_patch() Examples

The following are code examples for showing how to use jsonpatch.apply_patch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: invenio-checker-old   Author: dset0x   File: supervisor.py    GNU General Public License v2.0 6 votes vote down vote up
def handle_results(task_ids):
    """Commit patches.

    :type task_ids: list of str
    :param task_ids: values returned by `run_test` instances
    """
    with with_eliot(action_type='handle results', worker_id=task_ids[0]):
        for task_id in task_ids:
            redis_worker = RedisWorker(task_id)
            for recid, patches in redis_worker.all_patches.items():
                record = get_record_orig(recid)
                for patch in patches:
                    jsonpatch.apply_patch(record, patch, in_place=True)
                record.commit()
            redis_worker.master.rule.mark_recids_as_checked(redis_worker.bundle_requested_recids)
            redis_worker.status = StatusWorker.committed 
Example 2
Project: Paradrop   Author: ParadropLabs   File: hostconfig.py    Apache License 2.0 5 votes vote down vote up
def getHostConfig(update):
    """
    Load host configuration.

    Read device information from networkDevices.
    Store host configuration in hostConfig.
    """
    # TODO We need to check for changes in hardware.  If a new device was
    # added, we should try to automatically configure it.  If a device was
    # removed, we should be aware of what is no longer valid.
    devices = update.cache_get('networkDevices')
    config = prepareHostConfig(devices)

    # update.old is not guaranteed to contain the old host configuration, so
    # save a backup copy in update.new.  This will be used by revertHostConfig
    # if we need to back out.
    update.cache_set('oldHostConfig', config)

    # If this is a sethostconfig operation, then read the host config from the
    # update object.  Ordinary chute operations should not alter the host
    # configuration.
    if update.updateType == 'sethostconfig':
        config = update.hostconfig

    elif update.updateType == 'patchhostconfig':
        config = jsonpatch.apply_patch(config, update.patch)

    # For factoryreset, try to load the default configuration or automatically
    # generate a new one if the file is not found.
    elif update.updateType == 'factoryreset':
        config = prepareHostConfig(devices,
                hostConfigPath=settings.DEFAULT_HOST_CONFIG_FILE)

    update.cache_set('hostConfig', config) 
Example 3
Project: invenio-records   Author: inveniosoftware   File: api.py    MIT License 5 votes vote down vote up
def patch(self, patch):
        """Patch record metadata.

        :params patch: Dictionary of record metadata.
        :returns: A new :class:`Record` instance.
        """
        data = apply_patch(dict(self), patch)
        return self.__class__(data, model=self.model) 
Example 4
Project: watcher   Author: openstack   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            if p['path'].lstrip('/') not in doc:
                msg = _('Adding a new attribute (%s) to the root of '
                        ' the resource is not allowed')
                raise wsme.exc.ClientSideError(msg % p['path'])
    return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch)) 
Example 5
Project: zun   Author: kevin-zhaoshuai   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            attr = p['path'].lstrip('/')
            if attr not in doc:
                msg = _("Adding a new attribute %s to the root of "
                        "the resource is not allowed.") % p['path']
                raise wsme.exc.ClientSideError(msg)
            if doc[attr] is not None:
                msg = _("The attribute %s has existed, please use "
                        "'replace' operation instead.") % p['path']
                raise wsme.exc.ClientSideError(msg)
    return jsonpatch.apply_patch(doc, patch) 
Example 6
Project: iotronic   Author: MDSLab   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            if p['path'].lstrip('/') not in doc:
                msg = _('Adding a new attribute (%s) to the root of '
                        ' the resource is not allowed')
                raise wsme.exc.ClientSideError(msg % p['path'])
    return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch)) 
Example 7
Project: invenio-checker-old   Author: dset0x   File: worker.py    GNU General Public License v2.0 5 votes vote down vote up
def get_record_orig_or_mem(self, recid):
        # We upload patches at the end, so we're not picking up our own patches here

        # XXX Could put a lock around this but ugh.
        record = get_record_orig(recid)
        record_hash = hash(record)
        sorted_fullpatches = get_fullpatches(recid)

        for fullpatch in sorted_fullpatches:
            # FIXME: Check record hash? Or check in `get_fullpatches`?  see conftest2.py:408
            # assert fullpatch['record_hash'] == record_hash
            self.patches_we_applied_add(fullpatch)
            jsonpatch.apply_patch(record, fullpatch['patch'], in_place=True)
        return record 
Example 8
Project: openstack-iot   Author: digambar15   File: utils.py    Apache License 2.0 5 votes vote down vote up
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            if p['path'].lstrip('/') not in doc:
                msg = _('Adding a new attribute (%s) to the root of '
                        ' the resource is not allowed')
                raise wsme.exc.ClientSideError(msg % p['path'])
    return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch)) 
Example 9
Project: gnocchi   Author: gnocchixyz   File: api.py    Apache License 2.0 4 votes vote down vote up
def patch(self):
        # NOTE(sileht): should we check for "application/json-patch+json"
        # Content-Type ?

        try:
            rt = pecan.request.indexer.get_resource_type(self._name)
        except indexer.NoSuchResourceType as e:
            abort(404, six.text_type(e))
        enforce("update resource type", rt)

        # Ensure this is a valid jsonpatch dict
        patch = deserialize_and_validate(
            ResourceTypeJsonPatchSchema,
            expected_content_types=["application/json-patch+json"])

        # Add new attributes to the resource type
        rt_json_current = rt.jsonify()
        try:
            rt_json_next = jsonpatch.apply_patch(rt_json_current, patch)
        except jsonpatch.JsonPatchException as e:
            abort(400, six.text_type(e))
        del rt_json_next['state']

        # Validate that the whole new resource_type is valid
        schema = pecan.request.indexer.get_resource_type_schema()
        try:
            rt_json_next = voluptuous.Schema(schema.for_update, required=True)(
                rt_json_next)
        except voluptuous.Error as e:
            abort(400, "Invalid input: %s" % e)

        # Get only newly formatted and deleted attributes
        add_attrs = {k: v for k, v in rt_json_next["attributes"].items()
                     if k not in rt_json_current["attributes"]}
        del_attrs = [k for k in rt_json_current["attributes"]
                     if k not in rt_json_next["attributes"]]

        if not add_attrs and not del_attrs:
            # NOTE(sileht): just returns the resource, the asked changes
            # just do nothing
            return rt

        try:
            add_attrs = schema.attributes_from_dict(add_attrs)
        except resource_type.InvalidResourceAttribute as e:
            abort(400, "Invalid input: %s" % e)

        try:
            return pecan.request.indexer.update_resource_type(
                self._name, add_attributes=add_attrs,
                del_attributes=del_attrs)
        except indexer.NoSuchResourceType as e:
                abort(400, six.text_type(e))