[Python] What's the most efficient way to decode protobuf byte stream from a websocket in...

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have a websocket to a site which returns a protobuf byte stream. Im trying to find the most efficient way to decode the protobuf bytes. If I have the .proto schema definitions, what's the most efficient way to decode the byte stream considering each new websocket protobuf byte data could be any one of the classes generated from the .proto definition? I imagine the solution below would take a long time if there are maybe 1,000 classes.

    from message_pb2 import MsgTypeA, MsgTypeB, MsgTypeC

    def try_parse(binary_data):
    for MsgClass in [MsgTypeA, MsgTypeB, MsgTypeC]:
    msg = MsgClass()
    try:
    msg.ParseFromString(binary_data)
    # Optionally validate some required fields or structure
    print(f"Parsed as {MsgClass.__name__}: {msg}")
    return msg
    except Exception:
    continue
    raise ValueError("Unknown message format or failed to decode.")

    Continue reading...

Compartilhe esta Página