What is Protobuf and Why You Should Use It | by Jason Ngan | Feb, 2022

Proto Recordsdata

Picture by Pavel Danilyuk on Pexels
syntax = "proto3";

bundle person;

message Consumer
string title = 1;
int32 age = 2;
int32 top = 3;
repeated Pet pets = 4;

message Pet
string title = 1;
string sound = 2;

Protoc

Picture by Tima Miroshnichenko on Pexels
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/person.proto
....
_USER = _descriptor.Descriptor(
title='Consumer',
full_name='person.Consumer',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
....

Serialisation of Protobuf Object

Picture by cottonbro on Pexels
from pb.proto import user_pb2person = user_pb2.Consumer()
person.title = "Jason"
person.age = 20
person.top = 180
pet1 = person.pets.add()
pet1.title = "Canine"
pet1.sound = "Bark"
# Attribute error
person.pal = "Peter"
# Kind error
person.age = "twenty"
protoString = person.SerializeToString()parsedUserFromStr = user_pb2.Consumer()
parsedUserFromStr.ParseFromString(protoString)
print(protoString)
# b'nx05Jasonx10x14x18xb4x01"x0bnx03Dogx12x04Bark'
print(parsedUserFromStr)
# title: "Jason"
# age: 20
# top: 180
# pets
# title: "Canine"
# sound: "Bark"
#

Binary Encoding

Picture by Miguel A. Padrinan on Pexels

"title": "Jason",
"cash": 300
# jsonString = '"title": "Jason", "cash": 300'
message Particular person 
string title = 1;
int cash = 2;
125Jason20300
00000011 00000000 00000000
00000001 00101100

More Posts