繁体   English   中英

Python 3-Google protobuf响应-不带.proto文件的解码

[英]Python 3 - Google protobuf response - decode without .proto file

我有一个问题解码谷歌protobuf响应没有.proto文件,已实现与原型文件和工作正常,但在这种情况下.proto文件不可用。

使用python 3+并从隧道获得此响应

b'\x08\x00\x12\x88\x01\x08\xda\xc9\x06\x10\xb6\xc9\x03\x18\xa1\x8b\xb8\x01 \x00*\x00:\x00B\x00J\x00R\x00Z\x00b\x00j\x00r\x00z\x00\x80\x01\xe9\x9b\x8c\xb5\x99-\x90\x01d\x98\x01\xea\x9b\x8c\xb5\x99-\xa2\x01\x00\xaa\x01\x00\xb0\x01\x00\xb8\x01\x01\xc0\x0
1\x00\xd1\x01\x00\x00\x00\x00\x00\x00\x00\x00\xd9\x01\x00\x00\x00\x00\x00\x00\x00\x00\xe1\x01\x00\x00\x00\x00\x00\x00\x00\x00\xea\x01\x00\xf0\x01\x01\xf8\x01\x00\x80\x02\x00\x88\x02\x00\x90\x02\x00\x98\x02\x00\xa8\x02\x00\xb0\x02\x00\xb8\x02\x90N\xc0\x02\x00\xc8\x0
2\x00'

有一种方法可以解码谷歌ptobuf没有.proto文件,并使其成为一个字典?

我的代码实现如下:

import pika

credentials = pika.PlainCredentials('demo', 'demo')

cp = pika.ConnectionParameters(
    host='127.0.0.1',
    port=5671,
    credentials=credentials,
    ssl=False,
)

connection = pika.BlockingConnection(cp)
channel = connection.channel()

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback, queue='demo_queu', no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

需要实现:

获取身体并将其解码为人类可读的

任何想法将不胜感激

终于找到了我自己的解决方法,也许是一种原始方式,但只有这对我有用。

解:

1.列出了.proto文件中的所有描述符

    here is .proto file generated for python 3 is too big cant paste content here

    https://ufile.io/2p2d6

    descriptors = [proto_file.descriptor_1, proto_file.descriptor_2]

2.循环投掷列表并逐个传递

for d in descriptors:
    decoded_response = proto_file._reflection.ParseMessage(d, raw_response.body)

3.检查decoding_response是否为空白

   if decoded_response:
       # descriptor was found
       # response is decoded
   else:
       # no descriptor

4.解码后的响应我们将其解析为dict:

from protobuf_to_dict import protobuf_to_dict

decoded_response_to_dict = protobuf_to_dict(decoded_response)

这个花费数周时间的解决方案终于奏效了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM