當前位置: 首頁>>代碼示例>>Python>>正文


Python jsonpatch.apply_patch方法代碼示例

本文整理匯總了Python中jsonpatch.apply_patch方法的典型用法代碼示例。如果您正苦於以下問題:Python jsonpatch.apply_patch方法的具體用法?Python jsonpatch.apply_patch怎麽用?Python jsonpatch.apply_patch使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在jsonpatch的用法示例。


在下文中一共展示了jsonpatch.apply_patch方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: apply_jsonpatch

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
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)

        if (p['op'] == 'replace' and (p['path'] == '/labels' or
                                      p['path'] == '/health_status_reason')):
            try:
                val = p['value']
                dict_val = val if type(val) == dict else ast.literal_eval(val)
                p['value'] = dict_val
            except (SyntaxError, ValueError, AssertionError) as e:
                raise exception.PatchError(patch=patch, reason=e)
    return jsonpatch.apply_patch(doc, patch) 
開發者ID:openstack,項目名稱:magnum,代碼行數:24,代碼來源:utils.py

示例2: getHostConfig

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
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) 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:36,代碼來源:hostconfig.py

示例3: apply_data_patch

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
def apply_data_patch(item, changes):
    patch_changes = []
    prepare_patch(patch_changes, item, changes)
    if not patch_changes:
        return {}
    return _apply_patch(item, patch_changes) 
開發者ID:openprocurement,項目名稱:openprocurement.api,代碼行數:8,代碼來源:utils.py

示例4: apply_jsonpatch

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
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)) 
開發者ID:openstack,項目名稱:watcher,代碼行數:10,代碼來源:utils.py

示例5: get

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
def get(self, selector=None):
        """Main function for get command

        :param selector: the type selection for the get operation.
        :type selector: str.
        :returns: returns a list from get operation

        """
        results = list()

        instances = self.get_selection()
        if not instances or len(instances) == 0:
            raise NothingSelectedError()

        for instance in instances:
            currdict = instance.resp.dict

            # apply patches to represent current edits
            for patch in instance.patches:
                currdict = jsonpatch.apply_patch(currdict, patch)

            if selector:
                jsonpath_expr = jsonpath_rw.parse(u'%s' % selector)
                matches = jsonpath_expr.find(currdict)
                temp_dict = OrderedDict()

                for match in matches:
                    json_pstr = u'/%s' % match.full_path
                    json_node = jsonpointer.resolve_pointer(currdict, json_pstr)
                    temp_dict[str(match.full_path)] = json_node
                    results.append(temp_dict)
            else:
                results.append(currdict)

        return results 
開發者ID:HewlettPackard,項目名稱:python-ilorest-library-old,代碼行數:37,代碼來源:rmc.py

示例6: patch

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
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)) 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:55,代碼來源:api.py

示例7: get_version_diff

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
def get_version_diff(from_data, to_data):
    """Calculate the diff (a mangled JSON patch) between from_data and to_data"""

    basic_patch = jsonpatch.make_patch(from_data, to_data)
    result = []
    for operation in sorted(basic_patch, key=lambda o: (o['op'], o['path'])):
        op = operation['op']
        ignore = False
        # We deal with standing_in and party_memberships slightly
        # differently so they can be presented in human-readable form,
        # so match those cases first:
        m = re.search(
            r'(standing_in|party_memberships)(?:/([^/]+))?(?:/(\w+))?',
            operation['path'],
        )
        if op in ('replace', 'remove'):
            operation['previous_value'] = \
                jsonpointer.resolve_pointer(
                    from_data,
                    operation['path'],
                    default=None
                )

        attribute, election, leaf = m.groups() if m else (None, None, None)
        if attribute:
            explain_standing_in_and_party_memberships(operation, attribute, election, leaf)
        if op in ('replace', 'remove'):
            if op == 'replace' and not operation['previous_value']:
                if operation['value']:
                    operation['op'] = 'add'
                else:
                    # Ignore replacing no data with no data:
                    ignore = True
        elif op == 'add':
            # It's important that we don't skip the case where a
            # standing_in value is being set to None, because that's
            # saying 'we *know* they're not standing then'
            if (not operation['value']) and (attribute != 'standing_in'):
                ignore = True
        operation['path'] = re.sub(r'^/', '', operation['path'])
        if not ignore:
            result.append(operation)
        # The operations generated by jsonpatch are incremental, so we
        # need to apply each before going on to parse the next:
        operation['path'] = '/' + operation['path']
        from_data = jsonpatch.apply_patch(from_data, [operation])
    for operation in result:
        operation['path'] = operation['path'].lstrip('/')
    return result 
開發者ID:mysociety,項目名稱:yournextrepresentative,代碼行數:51,代碼來源:diffs.py

示例8: get_save

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import apply_patch [as 別名]
def get_save(self, selector=None, currentoverride=False, pluspath=False, \
                                                                onlypath=None):
        """Special main function for get in save command

        :param selector: the type selection for the get operation.
        :type selector: str.
        :param currentoverride: flag to override current selection.
        :type currentoverride: boolean.
        :param pluspath: flag to add path to the results.
        :type pluspath: boolean.
        :param onlypath: flag to enable only that path selection.
        :type onlypath: boolean.
        :returns: returns a list from the get command

        """
        results = list()

        instances = self.get_selection()
        if not instances or len(instances) == 0:
            raise NothingSelectedError()

        for instance in instances:
            if self.get_save_helper(instance.resp.request.path, instances)\
                                                     and not currentoverride:
                continue
            elif onlypath:
                if not onlypath == instance.resp.request.path:
                    continue

            currdict = instance.resp.dict

            # apply patches to represent current edits
            for patch in instance.patches:
                currdict = jsonpatch.apply_patch(currdict, patch)

            if selector:
                for item in currdict.iterkeys():
                    if selector.lower() == item.lower():
                        selector = item
                        break

                try:
                    jsonpath_expr = jsonpath_rw.parse(u'"%s"' % selector)
                except Exception, excp:
                    raise InvalidCommandLineError(excp)

                matches = jsonpath_expr.find(currdict)
                temp_dict = OrderedDict()

                for match in matches:
                    json_pstr = u'/%s' % match.full_path
                    json_node = jsonpointer.resolve_pointer(currdict, json_pstr)
                    temp_dict[str(match.full_path)] = json_node

                results.append(temp_dict)
            else:
                if pluspath:
                    results.append({instance.resp.request.path: currdict})
                else:
                    results.append(currdict) 
開發者ID:HewlettPackard,項目名稱:python-ilorest-library-old,代碼行數:62,代碼來源:rmc.py


注:本文中的jsonpatch.apply_patch方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。