Example #1
0
def get_pb():
    # create and fill test message
    pb = pb_test.TestMessage()
    pb.id = 123
    pb.b = b"\x08\xc8\x03\x12"
    pb.query = "some text"
    pb.flag = True
    pb.test_enum = 2
    msg = pb.nested_msg
    msg.id = 1010
    msg.title = "test title"
    msg.url = "http://example.com/"

    msgs = pb.nested_msgs.add()
    msgs.id = 456
    msgs.title = "test title"
    msgs.url = "http://localhost/"

    pb.rep_int.append(1)
    pb.rep_int.append(2)

    pb.bs.append(b"\x00\x01\x02\x03\x04")
    pb.bs.append(b"\x05\x06\x07\x08\x09")

    return pb
Example #2
0
def test_json_and_back(enum_string=False):
    # convert it to JSON and back
    pb = get_pb()
    pprint(pb.SerializeToString())
    json_obj = protobuf_json.pb2json(pb, enum_string=enum_string)
    pprint(json_obj)
    pb2 = protobuf_json.json2pb(pb_test.TestMessage(), json_obj)
    pprint(pb2.SerializeToString())
    assert pb == pb2
Example #3
0
#!/usr/bin/env python
# coding=utf-8
from pprint import pprint
import protobuf_json

import test_pb2 as pb_test

#create and fill test message
pb = pb_test.TestMessage()
pb.id = 123
pb.b = b"\x08\xc8\x03\x12"
pb.query = "some text"
pb.flag = True
pb.test_enum = 2
msg = pb.nested_msg
msg.id = 1010
msg.title = 'test title'
msg.url = 'http://example.com'

msags = pb.nested_msgs.add()
msags.id = 456
msags.title='test title22'
msags.url='http://localhost/'

pb.rep_int.append(1)
pb.rep_int.append(22)

pb.bs.append('\x00\x01\x02\x03\x04')
pb.bs.append('\x05\x06\x07\x08\x09')

pprint(pb.SerializeToString)
Example #4
0
#!/usr/bin/python

import os, sys, json
from pprint import pprint

import protobuf_json

import test_pb2 as pb_test

# create and fill test message
pb=pb_test.TestMessage()
pb.id=123
pb.flag=True
for i in xrange(1000):
    msgs=pb.nested_msgs.add()
    msgs.id=456
    msgs.title="test title"
    msgs.url="http://localhost/"

for i in xrange(100):
    pb.rep_int.append(i)

json_obj=protobuf_json.pb2json(pb)

with open('message.proto', 'w') as f:
    f.write(pb.SerializeToString())

with open('message.json', 'w') as f:
    f.write(json.dumps(json_obj))

Example #5
0
import test_pb2

if __name__ == "__main__":
    msg = test_pb2.TestMessage()
    msg.testEnum = 1
    msg.testInt = 100
    buf = msg.SerializeToString()

    with open("/tmp/proto.dat", "wb+") as fl:
        fl.write(buf)

    msg2 = test_pb2.TestMessage()
    msg2.ParseFromString(buf)
    print(msg2)