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


Python jsonpatch.make_patch方法代碼示例

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


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

示例1: prepare_patch

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import make_patch [as 別名]
def prepare_patch(changes, orig, patch, basepath=''):
    if isinstance(patch, dict):
        for i in patch:
            if i in orig:
                prepare_patch(changes, orig[i], patch[i], '{}/{}'.format(basepath, i))
            else:
                changes.append({'op': 'add', 'path': '{}/{}'.format(basepath, i), 'value': patch[i]})
    elif isinstance(patch, list):
        if len(patch) < len(orig):
            for i in reversed(range(len(patch), len(orig))):
                changes.append({'op': 'remove', 'path': '{}/{}'.format(basepath, i)})
        for i, j in enumerate(patch):
            if len(orig) > i:
                prepare_patch(changes, orig[i], patch[i], '{}/{}'.format(basepath, i))
            else:
                changes.append({'op': 'add', 'path': '{}/{}'.format(basepath, i), 'value': j})
    else:
        for x in make_patch(orig, patch).patch:
            x['path'] = '{}{}'.format(basepath, x['path'])
            changes.append(x) 
開發者ID:openprocurement,項目名稱:openprocurement.api,代碼行數:22,代碼來源:utils.py

示例2: get_revision_changes

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import make_patch [as 別名]
def get_revision_changes(dst, src):
    return make_patch(dst, src).patch 
開發者ID:openprocurement,項目名稱:openprocurement.api,代碼行數:4,代碼來源:utils.py

示例3: _prepare_request_body

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import make_patch [as 別名]
def _prepare_request_body(self, patch, prepend_key):
        if patch:
            if not self._store_unknown_attrs_as_properties:
                # Default case
                new = self._body.attributes
                original_body = self._original_body
            else:
                new = self._unpack_properties_to_resource_root(
                    self._body.attributes)
                original_body = self._unpack_properties_to_resource_root(
                    self._original_body)

            # NOTE(gtema) sort result, since we might need validate it in tests
            body = sorted(
                list(jsonpatch.make_patch(
                    original_body,
                    new).patch),
                key=operator.itemgetter('path')
            )
        else:
            if not self._store_unknown_attrs_as_properties:
                # Default case
                body = self._body.dirty
            else:
                body = self._unpack_properties_to_resource_root(
                    self._body.dirty)

            if prepend_key and self.resource_key is not None:
                body = {self.resource_key: body}
        return body 
開發者ID:openstack,項目名稱:openstacksdk,代碼行數:32,代碼來源:resource.py

示例4: document_needs_updating

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import make_patch [as 別名]
def document_needs_updating(enrollment):
    """
    Get the document from elasticsearch and see if it matches what's in the database

    Args:
        enrollment (ProgramEnrollment): A program enrollment

    Returns:
        bool: True if the document needs to be updated via reindex
    """
    index = get_default_alias(PRIVATE_ENROLLMENT_INDEX_TYPE)

    conn = get_conn()
    try:
        document = conn.get(index=index, doc_type=GLOBAL_DOC_TYPE, id=enrollment.id)
    except NotFoundError:
        return True
    serialized_enrollment = serialize_program_enrolled_user(enrollment)
    del serialized_enrollment['_id']
    source = document['_source']

    if serialized_enrollment != source:
        # Convert OrderedDict to dict
        reserialized_enrollment = json.loads(json.dumps(serialized_enrollment))

        diff = make_patch(source, reserialized_enrollment).patch
        serialized_diff = json.dumps(diff, indent="    ")
        log.info("Difference found for enrollment %s: %s", enrollment, serialized_diff)
        return True
    return False 
開發者ID:mitodl,項目名稱:micromasters,代碼行數:32,代碼來源:api.py

示例5: diff

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import make_patch [as 別名]
def diff(self, hash1, hash2=None, txid=None):
        branch = self._branches[txid]
        rev1 = branch[hash1]
        rev2 = branch[hash2] if hash2 else branch._latest
        if rev1.hash == rev2.hash:
            return JsonPatch([])
        else:
            dict1 = message_to_dict(rev1.data)
            dict2 = message_to_dict(rev2.data)
            return make_patch(dict1, dict2)

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tagging utility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
開發者ID:opencord,項目名稱:voltha,代碼行數:14,代碼來源:config_node.py

示例6: diffMsgs

# 需要導入模塊: import jsonpatch [as 別名]
# 或者: from jsonpatch import make_patch [as 別名]
def diffMsgs(self, msg1, msg2):
        msg1_dict = MessageToDict(msg1)
        msg2_dict = MessageToDict(msg2)
        diff = make_patch(msg1_dict, msg2_dict)
        return dumps(diff.patch, indent=2) 
開發者ID:opencord,項目名稱:voltha,代碼行數:7,代碼來源:flow_helpers.py

示例7: get_version_diff

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


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