Package: yc-protobuf3-to-dict
protobuf-to-dictprotobuf-to-dict is a small Python library for creating dicts from protocol
buffers. It is intended to be used as an intermediate step before
serialization (e.g. to JSON).InstallationNote: This is a fork. Install by pointing to this github repo.For example:pip install git@github.com:yepcord/protobuf-to-dict.gitExampleGiven thegoogle.protobuf.message.MessagesubclassMyMessage:>>>fromprotobuf3_to_dictimportprotobuf_to_dict,dict_to_protobuf>>>my_message=MyMessage()>>># pb_my_message is a protobuf string>>>my_message.ParseFromString(pb_my_message)>>>my_message_dict=protobuf_to_dict(my_message)>>>print(my_message_dict){'message':'Hello'}>>>msg=dict_to_protobuf(MyMessage,values=my_message_dict)>>>assertmsg==my_messageTrueDatetime conversionThis package automatically converts Python's datetime objects to Google's Timestamp and vice-versa.
If you want to manually do the conversion, the functions are:fromprotobuf3_to_dictimportdatetime_to_timestamp,timestamp_to_datetimetimestamp=datetime_to_timestamp(sample_datetime)result_sample_datetime=timestamp_to_datetime(timestamp)assertsample_datetime==result_sample_datetimeGetting all fields, field names and options of a protobuf classFor example in the tests folder you can find sample.proto:message Obj {
    int32 id = 1 [(is_optional) = true];
    string item_id = 2;
    google.protobuf.Timestamp transacted_at = 3;
    Status status = 5;
}Then you can:>>>fromprotobuf3_to_dictimportget_field_names_and_options>>>forfield,field_name,optionsinget_field_names_and_options(sample_pb2.Obj):...print('name:{}, options:{}'.format(field_name,options))name:id,options:{'is_optional':True}name:item_id,options:{}name:transacted_at,options:{}name:status,options:{}Validation for required fieldsProtobuf 3 does not have a notion of required vs. optional fields. Everything is optional. However if you need some sort of validation before converting your dictionary to a protobuf object, first of all you need to add an option to your protobuf messages that is calledis_optional. Note that this is different than theoptionalkeyword in Prorobuf 2. This is an "option":For example in the tests folder you can find sample.proto:message Obj {
    int32 id = 1 [(is_optional) = true];
    string item_id = 2;
    google.protobuf.Timestamp transacted_at = 3;
    Status status = 5;
}Then you can validate if a dictionary has all the fields you need:>>>importdatetime>>>fromprotobuf3_to_dictimportvalidate_dict_for_required_pb_fields>>>>>>dic={'item_id':2,'transacted_at':datetime.datetime.now(),'status':0}>>>fromtestsimportsample_pb2>>>validate_dict_for_required_pb_fields(pb=sample_pb2.Obj,dic=dic)But if you have missing fields:>>>dic={'item_id':2}>>>validate_dict_for_required_pb_fields(pb=sample_pb2.Obj,dic=dic)Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"protobuf-to-dict/protobuf_to_dict/convertor.py",line274,invalidate_dict_for_required_pb_fieldsraiseFieldsMissing('Missing fields:{}'.format(', '.join(missing_fields)))protobuf_to_dict.convertor.FieldsMissing:Missingfields:transacted_at,statusCaveatsThis library grew out of the desire to serialize a protobuf-encoded message toJSON. As JSON has no built-in binary type (all strings in
JSON are Unicode strings), any field whose type isFieldDescriptor.TYPE_BYTESis, by default, converted to a base64-encoded
string.If you want to override this behaviour, you may do so by passingprotobuf_to_dicta dictionary of protobuf types to callables via thetype_callable_mapkwarg:>>>fromcopyimportcopy>>>fromgoogle.protobuf.descriptorimportFieldDescriptor>>>fromprotobuf3_to_dictimportprotobuf_to_dict,TYPE_CALLABLE_MAP>>>>>>type_callable_map=copy(TYPE_CALLABLE_MAP)>>># convert TYPE_BYTES to a Python bytestring>>>type_callable_map[FieldDescriptor.TYPE_BYTES]=str>>>>>># my_message is a google.protobuf.message.Message instance>>>protobuf_to_dict(my_message,type_callable_map=type_callable_map)By default, the integer representation is used for enum values. To use their
string labels instead, passuse_enum_labels=Trueintoprotobuf_to_dict:>>>protobuf_to_dict(my_message,use_enum_labels=True)And if you need the enum labels to be automatically converted to lowercase:>>>protobuf_to_dict(my_message,use_enum_labels=True,lowercase_enum_lables=True)When you convert from dictionary to protobuf, if you need the enums to work both
in lowercase and uppercase, set thestrict=False.Testingpytest tests/To regeneratesrc/tests/sample_pb2.py:run thecompile.shfile inside the tests folder.attentionProrobuf 3.0.0 has supported json now.
Checkhttps://developers.google.com/protocol-buffers/docs/reference/python/for more details.Authorsprotobuf-to-dict is written and maintained byBen Hodgson, with significant contributions fromNino Walker,Jonathan Klaassen, andTristram Gräbener.Sep Dehpour(Un)licenseThis is free and unencumbered software released into the public domain.Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.For more information, please refer tohttp://unlicense.org/