I have a service that exposes two REST APIs which exchange protobuf messages (payload). Up until now, I've worked always with HTTP/JSON, and in Python by using the requests and json packages is very easy to make HTTP requests with a JSON payload. I'm struggling to understand how to make a request having a protobuf message in the payload. I think to have searched enough on the Internet without any significant result. Has somebody had experienced this? Can she/he share some example?
Specifically, I have a message_pb
which is the protobuf message object I instantiate (based on the python code generated by the protobuf-compiler) and fill in with my data.
I've tried to make a PUT request by using the requests package as follows:
requests.put(url, data=message_pb, header={'Content-Type': 'application/octet-stream'})
This is the Traceback I received:
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
import sys import myprotocol_pb2 as proto import varint # (this is the varint.py file) data = open("filename. bin", "rb"). read() # read file as string decoder = varint. decodeVarint32 # get a varint32 decoder # others are available in varint.py next_pos, pos = 0, 0 while pos < len(data): msg = proto.
Protocol buffers (Protobuf) are a language-agnostic data serialization format developed by Google. Protobuf is great for the following reasons: Low data volume: Protobuf makes use of a binary format, which is more compact than other formats such as JSON. Persistence: Protobuf serialization is backward-compatible.
Zaytsev Dmitry's comments seemed to do the trick for me.
resp = requests.put(url, headers={'Content-Type': 'application/protobuf'}, data=message_pb.SerializeToString())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With