protobuf_to_pydantic icon indicating copy to clipboard operation
protobuf_to_pydantic copied to clipboard

Support `BaseModel` serialization to `Protobuf Message`

Open so1n opened this issue 2 years ago • 2 comments

The current step of converting BaseModel to Protobuf Message is tedious and has poor performance. e.g:

from google.protobuf.json_format import ParseDict
from pydantic import BaseModel
from demo_pb2 import DemoMessage

class Demo(BaseModel):
    pass


ParseDict(Demo().dict(), DemoMessage())

Serialization can be optimized in the following ways:

  • 1.Convert directly to Message:

    from protobuf_to_pydantic.p2p_model import P2PBaseModel
    
    class Demo(P2PBaseModel):
        pass
    
    Demo().to_message()
    
  • 2.Serialized to dict, then converted to Message by the developer (https://github.com/pydantic/pydantic/issues/1409#issuecomment-1376406994)

    from google.protobuf.json_format import ParseDict
    from pydantic import BaseModel
    from demo_pb2 import DemoMessage
    
    class Demo(BaseModel):
        pass
    
    
    DemoMessage(**Demo().dict())
    

so1n avatar Apr 16 '23 17:04 so1n

So yeah came here to use this to convert from protobuf to model and am stumped as there isn't really strong documentation for more complex multi-level models or submessage types. Love that this generates all the models so easily so big thank you!

mikey0000 avatar May 09 '24 10:05 mikey0000

@mikey0000 Protobuf's JsonFormat implementation is more complex there are many cases that can not be dealt with, you need to modify his code to achieve. So I will delay the implementation of this feature.

so1n avatar May 09 '24 16:05 so1n