GitHub仓库地址:https://github.com/protocolbuffers/protobuf
Google文档:https://developers.google.com/protocol-buffers/
https://docs.qq.com/doc/DV2t5TWhvZ21Eend6
protobuf安装
GitHub release页面下载:
将win64解压,bin目录添加进入环境变量,可以使用protoc.exe来生成相关类
解压protobuf-python-3.20.1.zip,进入其python目录
运行命令
python setup.py build
python setup.py install
安装成功后可以正常导入 import google.protobuf
安装gprc相关依赖
pip install grpcio #gRPC 的安装
pip install protobuf #ProtoBuf 相关的 python 依赖库(可以使用上一步中的编译安装、也可以这种安装方式)
pip install grpcio-tools #python grpc 的 protobuf 编译工具(有了这个也不需要装上面的protoc了)
grpc通信
编写proto文件
syntax = "proto3";
package challenge;
message request {
uint32 page =1;
uint64 time = 2;
string sign =3;
}
message response {
repeated string msg = 1;
}
service Challenge{
rpc SayHello (request) returns (response) {}
}
package、service、rpc等字段控制的是访问路径
命令来编译
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. .\yrx.proto
会生成yrx_pb2.py与yrx_pb2_grpc.py
grpc请求代码
import grpc
import yrx_pb2
import yrx_pb2_grpc
HOST = '0.0.0.0'
PORT = '9901'
def main():
conn = grpc.insecure_channel(HOST + ':' + PORT)
client = yrx_pb2_grpc.ChallengeStub(channel=conn)
page_time = "1:1652586112285"
sign = "92979f42250a942b"
page = page_time.split(":")[0]
time = page_time.split(":")[1]
response = client.SayHello(yrx_pb2.request(page=int(page), time=int(time), sign=sign))
print(str(response))
if __name__ == '__main__':
main()
protobuf序列化
编写proto文件
syntax = "proto3";
message msg{
string sign = 3;
}
命令来编译
protoc –python_out=. yrx.proto
会生成yrx_pb2.py
之后编写序列化代码
import yrx_pb2
def write():
msg = yrx_pb2.msg()
msg.sign = "24012a9b6a812b96"
result = msg.SerializeToString()
print("encode: ",result)
with open("pro.bin", "wb") as f:
f.write(result)
def read():
result = 0
with open("pro.bin", "rb") as f:
result = f.read()
msgb = yrx_pb2.msg()
msgb.ParseFromString(result)
print("decode: ",msgb.sign)
write()
read()
运行结果
encode: b'\x1a\x1024012a9b6a812b96'
decode: 24012a9b6a812b96