Protobuf python tutorial for stupid people like me

1. Why it

Java? Sucks! PHP? Sucks! C? Sucks! Rust? Sucks! Kotlin? Sucks! Golang? Sucks! C++? Sucks!
Anyway, for any programming language, as long as I don't know it well, I would think it's very hard to use. Even if I can use it with hard google searching, that doesn't mean I'm good at it. If you want me to write a good data structure with a programming language that I don't know well, I'll quit this game.

2. A simple protobuf file (it's more like a definition for a data structure)

```
syntax = "proto3";

message OneDay {
    string date = 1;

    message Content {
        repeated string text = 1;
    }
    Content content = 2;
}
```

3. Let's compile it to a python module

protoc --python_out=. ./oneday.proto

4. Let's use it with python

```
import oneday_pb2
oneday = oneday_pb2.OneDay()

oneday.date = "4.10"

oneday.content.text.append("yingshaoxo says:")
oneday.content.text.append("hi")
oneday.content.text.append("everyone")
oneday.content.text.append("!")

print(oneday)
print(oneday.content)
print(oneday.SerializeToString())
```

5. The result we were getting is:

```
date: "4.10"
content {
  text: "yingshaoxo says:"
  text: "hi"
  text: "everyone"
  text: "!"
}

text: "yingshaoxo says:"
text: "hi"
text: "everyone"
text: "!"

b'\n\x044.10\x12#\n\x10yingshaoxo says:\n\x02hi\n\x08everyone\n\x01!'

```

6. Conclusion

Actually, I think it's just a way to encode dict-list mixed data to strings so that we can send it through the network.

Comments

  1. Another example:


    everyday.proto
    ```
    //protoc --python_out=. everyday.proto
    syntax = "proto3";

    message OneDay {
    string date = 1;

    message Content {
    string text = 1;
    bytes image = 2;
    }
    repeated Content content = 2;
    }

    message EveryDay {
    repeated OneDay oneday = 1;
    }
    ```


    everyday.py
    ```
    import everyday_pb2
    oneday = everyday_pb2.OneDay()

    oneday.date = "4.10"

    content = oneday.Content()
    content.text = "hi"
    oneday.content.extend([content])

    content = oneday.content.add()
    content.image = b"hello"

    print(oneday)
    for i in oneday.content:
    if i.text:
    print("the text value: ", i.text)
    elif i.image:
    print("the image value: ", i.image)

    print()
    print('-'*20)
    print()

    saved_string = oneday.SerializeToString()
    print(saved_string)
    print()
    oneday = everyday_pb2.OneDay()
    oneday.MergeFromString(saved_string)
    print(oneday)
    ```

    ReplyDelete

Post a Comment