Created
February 7, 2021 02:54
-
-
Save jclosure/16b394b990033ce46bafa7b1708b8c5b to your computer and use it in GitHub Desktop.
Generic Python Protobuf <-> Dictionary: encoder/decoder functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from google.protobuf.json_format import MessageToDict | |
from google.protobuf.json_format import ParseDict | |
def encode(dictObj, pb_class): | |
"""Takes in a dict and returns the serialized binary of pb_class""" | |
# pb = dict_to_protobuf(pb_class, dict) | |
pb = pb_class() | |
pb = ParseDict(dictObj, pb, ignore_unknown_fields=True) | |
return pb.SerializeToString() | |
def decode(bin, pb_class): | |
"""Takes the serialized {value for value in variable}binary of an instance of the pb_class and returns a dict""" | |
pb = pb_class() | |
pb.ParseFromString(bin) | |
return MessageToDict(pb, including_default_value_fields=True, preserving_proto_field_name=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment