需要为原型消息格式转换python dict for gRPC

时间:2018-02-13 18:31:34

标签: python grpc proto

我有这样的格式,并希望将我的python dict转换为此proto格式 原型代码:

message template{

 message NicSettings{
    string network_adapter = 1;
    string network_name = 2;
 }

 message NetConfig{
    bool keep_mac_address =1;
    bool same_as_source = 2;
   repeated  NicSettings nic_settings = 3;
 }

 NetworkConfig network_config = 3;

}

python dict:

 template:
  { keepMacAddress: true, 
    sameAsSource : false, 
    nicSettings: [ {networkAdapter: "ethernet0", 
                    networkName: "Calpal1"
                    } ,
                    {networkAdapter: "ethernet1", 
                    networkName: "Calpal2"
                    } 
                 ] 
   }

如何将其转换为proto消息以将其传递给gRPC。

1 个答案:

答案 0 :(得分:0)

您的.proto是否正确(或者是否存在拼写错误?)并不完全清楚,但这看起来应该是符合

的内容

my_template_message = my_message_module_pb2.template( keep_mac_address=my_dictionary['keepMacAddress'], same_as_source=my_dictionary['sameAsSource'], nic_settings=tuple( my_message_module_pb2.template.NicSettings( network_adapter=my_subdictionary['networkAdapter'], network_name=my_subdictionary['networkName']) for my_subdictionary in my_dictionary['nicSettings'] ) ) 。在.proto内容中,您在另一个消息定义中嵌套了两个消息定义,这有点奇怪 - 这看起来根本不必要。