# 安装 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