Python 处理Protobuf协议
安装protobuf
- 使用Home Brew安装Protobuf:
brew install protobuf
- 查看是否安装成功
protoc --version
生成pb文件
- 进入文件路径命令行执行
protoc --python_out=./ ./HT_moment_body.proto
- 此时会在当前目录下生成:HT_moment_body_pb2.py
- 执行命令后生成的 pb 文件中并没有方法和类,导致报错;
- 因新版本的 grpc_tools 不直接生成定义了,而是运行中动态生成,所以还是可以正常运行的。
🌰
from proto import HT_moment_body_pb2
from common.configHTTP import myhttp
from common.getJwt import get_authorization
from google.protobuf import json_format
import json
#请求
expose_record =HT_moment_body_pb2.GetExposeRecordRequest()
#请求值赋值
expose_record.userid =10283233
expose_record.filter = 2
expose_record.ostype = 0
expose_record.version =327684
expose_record.area_code =b'CN'
###数据编译为字节流
data = expose_record.SerializeToString()
url = "/v1/moment/expose_record"
get_headers = {
'Authorization': get_authorization(10283233),
'Content-type': 'application/x-protobuf'
}
response = myhttp().main_http("post", url, data=data, headers=get_headers)
#返回
res = HT_moment_body_pb2.GetExposeRecordResponse()
###字节流转对象
res.ParseFromString(response.content)
print(res)
字节传输
- expose_record.area_code =b'CN'
JSON ->protobuf
from google.protobuf import json_format
import json
req={
'userid': 10283233,
'filter': 2,
'ostype': 0,
'version': 327684,
'area_code': "CN"
}
#json->字符串->字节流
expose_record = json_format.Parse(json.dumps(req),HT_moment_body_pb2.GetExposeRecordRequest())