# 安裝 protobuf 庫
pip install protobuf
# 安裝 protoc 編譯器(用于生成代碼)
# - Windows:從 https://github.com/protocolbuffers/protobuf/releases 下載
# - macOS:brew install protobuf
# - Linux:apt install protobuf-compiler
syntax = "proto3"; // 指定 proto 版本(proto3 是最新版本)
// 定義一個用戶消息結構
message User {
int32 id = 1; // 整數類型(字段編號 1)
string name = 2; // 字符串類型(字段編號 2)
bool is_active = 3; // 布爾類型(字段編號 3)
repeated string hobbies = 4; // 重復字段(類似數組,字段編號 4)
// 嵌套消息
message Address {
string city = 1;
string street = 2;
}
Address address = 5; // 嵌套類型字段
}
// 定義一個請求消息
message GetUserRequest {
int32 user_id = 1;
}
// 定義一個響應消息
message GetUserResponse {
User user = 1;
string status = 2;
}
// 定義服務(用于 RPC)
service UserService {
rpc GetUser(GetUserRequest) returns (GetUserResponse);
}
生成 Python 代碼
protoc --python_out=. message.proto #執行后會生成 message_pb2.py 文件,可在 Python 中導入使用
使用
import message_pb2
# 創建 User 消息
user = message_pb2.User()
user.id = 1
user.name = "Alice"
user.is_active = True
user.hobbies.append("reading")
user.address.city = "Beijing"
# 序列化為二進制
user_bytes = user.SerializeToString()
# 解析二進制
new_user = message_pb2.User()
new_user.ParseFromString(user_bytes)
print(new_user.name) # 輸出:Alice