本文整理匯總了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)
示例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)
示例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)
示例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))
示例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
示例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))
示例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
示例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)