Protocol buffers--python 实践

Protocol Buffers 是google开发的一个可以序列化 反序列化object的数据交换格式,类似于xml,但是比xml 更轻,更快,更简单。而且和xml json等数据序列化一样,跨平台跨语言。

安装

  1. 直接从 github 上下载整个项目 protobuf
  2. 解压,进入到 python 目录下
  3. Build and run the tests:
python setup.py build
python setup.py test
  1. Install:
python setup.py install

使用

简易使用。

  1. 在 hello.proto 文件中定义数据格式:
syntax = "proto3";

package hello;

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}
  1. 使用命令,在当前路径下生成 hello_pb2.py 文件:
protoc -I . --python_out=. hello.proto
  1. 然后就可以用生成好的类对数据进行序列化反序列化:
import hello_pb2

a = hello_pb2.SearchRequest()
a.query = 'hello'
a.page_number = 2
a.result_per_page = 10

ss = a.SerializeToString()

oo = hello_pb2.SearchRequest()
oo.ParseFromString(ss)

print(oo.query)
print(oo.page_number)
print(oo.result_per_page)

## output
hello
2
10

reference:
https://www.cnblogs.com/piperck/p/6290147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值