我有一个服务,它公开了两个交换protobuf消息(有效负载)的REST API。到目前为止,我一直使用HTTP / JSON,并且在Python中使用请求和json包非常容易使用JSON有效负载进行HTTP请求。我很难理解如何在有效负载中发出一个带有protobuf消息的请求。我认为在互联网上搜索得不够,没有任何重大结果。 有人经历过这个吗?她/他可以分享一些例子吗?
具体来说,我有一个message_pb
,它是我实例化的protobuf消息对象(基于protobuf编译器生成的python代码)并填写我的数据。
我尝试使用请求包发出PUT请求,如下所示:
requests.put(url, data=message_pb, header={'Content-Type': 'application/octet-stream'})
这是我收到的回溯:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/requests/api.py", line 126, in put
return request('put', url, data=data, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py", line 460, in send
for i in request.body:
TypeError: 'ObjectStatistics' object is not iterable
答案 0 :(得分:2)
扎伊采夫·德米特里(Zaytsev Dmitry)的评论似乎对我有用。
resp = requests.put(url, headers={'Content-Type': 'application/protobuf'}, data=message_pb.SerializeToString())