简体   繁体   English

如何在python中动态膨胀protobuf对象?

[英]How do I dynamically inflate a protobuf object in python?

I'm accessing a web service that provides 1) a protobuf schema and 2) binary data of a given protobuf message. 我正在访问一个Web服务,它提供1)protobuf模式和2)给定protobuf消息的二进制数据。 The protobuf schema is retrieved in ZIP format, and contains a .proto file that is defined roughly as: protobuf模式以ZIP格式检索,并包含一个大致定义为的.proto文件:

message FooMessage {
  //stuff
  ... 
}

//other .proto fun... 

Once I've fetched the .proto file, I compile it: 一旦我获取了.proto文件,我就编译它:

protoc --python_out=. path/to/message

And then I import the module: 然后我导入模块:

module = importlib.import_module(libName, package=pkg)

The next step is to go and fetch the binary data for the given object. 下一步是去获取给定对象的二进制数据。 I do that and store it as a data = io.BytesIO object. 我这样做并将其存储为data = io.BytesIO对象。

So now I want to inflate the FooMessage object with my fetched binary data that is defined in the .proto file, ala: 所以现在我想用我在.proto文件中定义的获取的二进制数据来扩充FooMessage对象,ala:

obj = module.FooMessage(data) 

Questions: 问题:

  1. How can I retrieve the FooMessage class name from the module that I've imported so that I can build the objects dynamically? 如何从我导入的module中检索FooMessage类名,以便我可以动态构建对象?
  2. Even if I "cheat" and look at the compiled code for a single .proto file, I don't see an obvious way to pass in the binary data to inflate the FooMessage_pb2.py object. 即使我“欺骗”并查看单个.proto文件的编译代码,我也没有看到传递二进制数据以夸大FooMessage_pb2.py对象的明显方法。 There doesn't seem to be a method that would take in the binary data to instantiate the object ala: obj = module.FooMessage(data) 似乎没有一种方法可以接受二进制数据来实例化对象ala: obj = module.FooMessage(data)

Clearly I'm doing / thinking about this in the wrong way. 显然,我正在以错误的方式思考/思考这个问题。 I would greatly appreciate the help. 我非常感谢你的帮助。

For #1, they include the class name in the schema. 对于#1,它们在模式中包含类名。 I just missed it. 我错过了它。

Well, for #2, I just need to use the module.FooMessage.FromString(data) method which was not immediately obvious in the documentation. 好吧,对于#2,我只需要使用module.FooMessage.FromString(data)方法,这在文档中并不是很明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM