【发布时间】:2019-06-17 17:44:18
【问题描述】:
我正在尝试在 python 中使用 protobuf 读取一些数据流,并且我想使用 trio 来制作客户端来读取流。 protobuf 有一些方法调用,我发现当我使用三重流时它们不起作用。
Linux 机器上的 Python 客户端。
import DTCProtocol_pb2 as Dtc
async def parent(addr, encoding, heartbeat_interval):
print(f"parent: connecting to 127.0.0.1:{addr[1]}")
client_stream = await trio.open_tcp_stream(addr[0], addr[1])
# encoding request
print("parent: spawing encoding request ...")
enc_req = create_enc_req(encoding) # construct encoding request
await send_message(enc_req, Dtc.ENCODING_REQUEST,client_stream, 'encoding request') # send encoding request
log.debug('get_reponse: started')
response = await client_stream.receive_some(1024)
m_size = struct.unpack_from('<H', response[:2]) # the size of message
m_type = struct.unpack_from('<H', response[2:4]) # the type of the message
m_body = response[4:]
m_resp = Dtc.EncodingResponse()
m_body 将是一些字节数据,我不知道如何解码。 Dtc.EncodingResponse() 是 protobuf 方法,它会给出一个 Dtc 对象,其中包含可读格式的响应。 (Dtc 是 protobuf 文件)。但我在这里什么也得不到。当我在没有三重奏的情况下执行此脚本时,Dtc.EncodingResponse() 将以可读格式给出完整的响应。
我猜问题是“client_stream”是一个只读取字节的三重流对象,所以我可能需要使用ReceiveChannel 对象。但如果这是真的,我不知道该怎么做。
更新: Nathaniel J. Smith 下面的答案解决了我的问题。
m_resp = Dtc.EncodingResponse()
m_resp.ParseFromString(m_body)
我觉得很傻,但是我之前没有 ParseFromString 数据,仅此而已。非常感谢所有回复的人。希望这对那里的人有所帮助。
【问题讨论】:
-
我编辑了这个问题,我要告诉你一些事情:永远不要为成为“菜鸟”而道歉。学习很好!
-
谢谢!真的很感谢鼓励!
-
虽然我完全同意 @M.K 关于为自己是新手而道歉的观点,但我认为删除从
# encoding request开始的代码行的缩进会破坏代码。名称client_stream是在parent协程的本地范围内创建的,但现在可以在其外部访问。此外,以parent:开头的print在某种程度上暗示这仍然应该是coro 主体的一部分。你能验证一下吗? -
@shmee ,你是对的。我的代码格式错误。我已经编辑了正确的空格。感谢您热情温和的建议。
标签: python protocol-buffers python-trio