![](/img/trans.png)
[英]Convert Python generated protobuf to java without .proto file
[英]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.