我想对内容类型为protobuf的python对象的API响应进行反序列化,我使用ParseFromString方法来解析HTTP响应,但只得到一个数字23,直接打印响应内容是b'nx08Hi,py-pb'
。那么,如何反序列化对python对象的HTTP响应呢?
proto file content:
syntax = "proto3";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
python代码:
# _*_ coding: utf8 _*_
from google.protobuf.json_format import ParseDict, MessageToJson
from protos.greet_pb2 import HelloRequest, HelloReply
import httpx
import asyncio
async def send_req():
req = {'name': 'py-pb'}
msg = ParseDict(req, HelloRequest())
print(msg)
print(type(msg))
print(msg.SerializeToString())
async with httpx.AsyncClient() as client:
resp = await client.post('http://localhost:5044/greet/Greeter/SayHello', data=msg.SerializeToString(),
headers={'Accept': 'application/protobuf', 'Content-Type': 'application/protobuf'})
print('=========response=========')
# print(resp.stream)
# print(resp.content)
# print(resp.text)
resp_msg = HelloReply().ParseFromString(resp.content)
# resp_msg = HelloReply().SerializeToString(resp.content)
print(resp_msg)
asyncio.run(send_req())
版本号:Python - 3.10.5
google。Protobuf - 4.21.2
相关回答:
ParseFromString is a method -- it does not return anything, but rather fills in self with the parsed content.
参考:Google协议缓冲区(protobuf)在Python3 -麻烦ParseFromString (encoding?)
ParseFromString
是一个实例方法。所以你想,例如:
hello_reply = HelloReply()
hello_reply.ParseFromString(resp.content)
文档包括一个使用ParseFromString
的示例。
这里有一个副本:
from google.protobuf.json_format import ParseDict, MessageToJson
from greet_pb2 import HelloRequest, HelloReply
rqst = {'name': 'py-pb'}
msg = ParseDict(rqst, HelloRequest())
tx = msg.SerializeToString()
print(tx)
print(tx.hex())
resp = HelloReply()
resp.ParseFromString(tx)
print(resp)
收益率:
b'nx05py-pb'
0a0570792d7062
message: "py-pb"
您可以将二进制作为十六进制,并将其插入protogen
进行解码。
Field #1: 0A String Length = 5, Hex = 05, UTF8 = "py-pb"