最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Update a prepackaged Protobuf message from **args - Stack Overflow

programmeradmin3浏览0评论

I have a Python function that sends pre-canned Protobuf messages based on a command id that's passed in. I also need to be able to modify fields in that message based on **args that are passed into the function:

def sendCmd(self, id, **args):
    cmdType = mod_commandToMessage[id] # Find command template
    cmd = cmdType() # instantiate command message
    # Apply parameters
    updateArgs(cmd, args)
    ...

def updateArgs(self, cmd:message, args):
    for key in args:
        if type(cmd) == google._upb._message.RepeatedCompositeContainer:
            if (len(cmd) == 0):
                obj = cmd.add()
                self.updateArgs(obj, args, level=level + 1)
        elif args[key] == None:
            pass
        elif isinstance(args[key], message):
            pass
        else:
            if isinstance(args[key], dict):
                self.updateArgs(getattr(cmd, key), args[key], level=level + 1)
            else:
                    setattr(cmd, key, args[key])

This works great if I call sendCmd like

mod_com.sendCmd(study_pb2.STUDY_LIST, type='xxx') 

The protobuf message type is passed in, translated to a message template and then instantiates it. updateArgs() then walks through the message replacing fields based on the args name (I probably could have used a dict for this, but I'm exploring Python and **args looked interesting).

Problem is that some of my canned messages contain submessages. To get around this I've tried several possibilities, the most recent was to create the updated submessage and attempt to pass it in via the args and then plug it into the base message. Unfortunately Protobuf won't let me simply overwrite the submessage, I need to use CopyFrom. I tried this in updateArgs():

attr=getattr(cmd, key)
if isinstance(attr, google.protobuf.message.Message):
    attr.CopyFrom(args[key])
else:
    setattr(cmd, key, args[key])

But now I when I hit my Timestamp submessage get the error:

TypeError: Parameter to MergeFrom() must be instance of same class: expected <class 'timestamp_pb2.Timestamp'> got <class 'google._upb._message.MessageMeta'>.

Protobuf seems to have some interesting ideas on how to create object hierarchies under the covers.

Any ideas where I'm going wrong here? Any better ways to do this?

.Proto file:

message StudyStart {
  string name = 1;
  string filename = 2;
  bool compressed = 3;
  int32 period = 4;
  int32 cycles = 5;
  google.protobuf.Timestamp timeToStart = 6;  // Time to start
发布评论

评论列表(0)

  1. 暂无评论