Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a http request with a protobuf payload in Python

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
like image 264
Jominer Avatar asked Oct 26 '17 08:10

Jominer


People also ask

How do I read a proto file in Python?

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.

What is Protobuf in Python?

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.


1 Answers

Zaytsev Dmitry's comments seemed to do the trick for me.

resp = requests.put(url, headers={'Content-Type': 'application/protobuf'}, data=message_pb.SerializeToString())
like image 197
rectrec369 Avatar answered Oct 16 '22 08:10

rectrec369