如何在protobuf消息中实现hash方法?

问题描述 投票:0回答:1

我制作了一个

Message.proto
文件并编译生成python文件,命名为
message_pb2
。 然后在一个场景中,我想将消息对象放入一个集合中,以使它们独一无二。 但是protobuf消息的
__hash__
函数引发了一个TypeError,那么我想我可以在我的代码中实现并重写这个函数。

我新建了一个继承

message_pb2.Message()
的类,但是运行代码时,又出现了一个错误:

KeyError: 'DESCRIPTOR'

现在我没有其他想法了!

python-3.x protocol-buffers
1个回答
0
投票

我做了一些更改并使用下面的代码,它起作用了:

import hashlib
from myproto_pb2 import MyMessage  # Import your generated protobuf message class

class HashableMessage:
    def __init__(self, message):
        self._message = message

    def __hash__(self):
        # Define the fields to include in the hash calculation
        fields_to_hash = [self._message.field1, self._message.field2, self._message.field3]

        # Convert the field values to bytes and concatenate them
        data = b"".join(str(field).encode() for field in fields_to_hash)

        # Calculate the hash value using SHA-256
        hash_value = hashlib.sha256(data).hexdigest()

        return int(hash_value, 16)  # Convert the hex hash to an integer

    def __eq__(self, other):
        return isinstance(other, HashableMessage) and self._message == other._message

# Create a set to store protobuf messages
message_set = set()

# Create an instance of the protobuf message
protobuf_message1 = MyMessage()
protobuf_message1.field1 = "value1"
protobuf_message1.field2 = 42
protobuf_message1.field3 = True


message_set.add(HashableMessage(protobuf_message1))

© www.soinside.com 2019 - 2024. All rights reserved.