Python 通过Cloud PubSub发布时反序列化协议缓冲区消息时出错

Python 通过Cloud PubSub发布时反序列化协议缓冲区消息时出错,python,protocol-buffers,google-cloud-pubsub,Python,Protocol Buffers,Google Cloud Pubsub,我试图通过Cloud Pub Sub发布protobuf消息,我遇到的问题是将protobuf消息序列化并反序列化到通过pubsub发送所需的字节字符串中 下面是我代码的相关部分,我将Protobuf对象传递给publish_price,从那里您可以看到我在序列化消息后尝试发布消息。在回调方法中返回结果后,我可以在反序列化端进行处理 # # Publish price def publish_price(price_obj): new_price_obj = price_obj.Ser

我试图通过Cloud Pub Sub发布protobuf消息,我遇到的问题是将protobuf消息序列化并反序列化到通过pubsub发送所需的字节字符串中

下面是我代码的相关部分,我将Protobuf对象传递给publish_price,从那里您可以看到我在序列化消息后尝试发布消息。在回调方法中返回结果后,我可以在反序列化端进行处理

 # # Publish price
def publish_price(price_obj):
    new_price_obj = price_obj.SerializeToString()
    

    future = publisher.publish(topic_path, new_price_obj)
    future.add_done_callback(get_callback(future, new_price_obj))

def get_callback(f, data):
        def callback(f):
            try:
                print(str(f.result(), 'utf-8'))
                # print(f.result())
                
            except:  # noqa
                print(data.FromString())
                print("Please handle {} for {}.".format(f.exception(), data))

        return callback
下面是相关的错误消息

Exception in thread Thread-CommitBatchPublisher:
[server] Traceback (most recent call last):
[server]   File "/app/app.py", line 39, in callback
[server]     print(str(f.result(), 'utf-8'))
[server] TypeError: decoding str is not supported
[server]
[server] During handling of the above exception, another exception occurred:
[server]
[server] Traceback (most recent call last):
[server]   File "/usr/local/lib/python3.9/threading.py", line 954, in _bootstrap_inner
[server]     self.run()
[server]   File "/usr/local/lib/python3.9/threading.py", line 892, in run
[server]     self._target(*self._args, **self._kwargs)
[server]   File "/usr/local/lib/python3.9/site-packages/google/cloud/pubsub_v1/publisher/_batch/thread.py", line 292, in _commit
[server]     future.set_result(message_id)
[server]   File "/usr/local/lib/python3.9/site-packages/google/cloud/pubsub_v1/futures.py", line 159, in set_result
[server]     self._trigger()
[server]   File "/usr/local/lib/python3.9/site-packages/google/cloud/pubsub_v1/futures.py", line 186, in _trigger
[server]     callback(self)
[server]   File "/app/app.py", line 43, in callback
[server]     print(data.ParseFromString())
[server] AttributeError: 'bytes' object has no attribute 'ParseFromString'

看起来,
data
是要解析的bytestring对象
bytes
是Python标准库中的一个类,它不了解协议缓冲区,也没有
ParseFromString
方法。这是protobuf类拥有的方法

FromString
是在proto类中声明的方法。假设
ResponseProto
是要分析的类型:

def parse_response(data: bytes):
    response = ResponseProto.FromString(data)
    return response