jeudi 12 avril 2018

How to dynamically instantiate a protobuf object with oneof fields

I have a protobuf message defined something like this

message data {
  user string = 1;
  oneof event {
     server.login login = 1;
     server.register register = 2;
     server.delete delete = 3;
  }
}

Now I have a function in python

def create_data_object(self, event)

Now the event could instance of the protos

server.login
server.register
server.delete

Now depending upon the type of proto it is like login,register or delete I want to create a data object something like

dataobject = data(user="someuser", {type}=event)

where type needs to be determined from the passed event object.

Now note that I can do it with something like

type = event.DESCRIPTOR.full_name

And then use some sort of switch condition and instantiate the object accordingly. However, I don't want to go this route because I will have to update the library everything I add a new event type.

I want it to determine the field to be used for the type parameter looking at the event.DESCRIPTOR.full_name and figure out the corresponding field from the data proto

How can I do this in python?





Aucun commentaire:

Enregistrer un commentaire