PYTHON讀寫PB
前期准備
-
官方protobuf定義:
-
python使用指南:
1.https://developers.google.com/protocol-buffers/docs/pythontutorial
2.http://blog.csdn.net/love_newzai/article/details/6906459 -
安裝 python對protobuf的支持:
1.wget https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.bz2
2.tar -vxjf protobuf-2.5.0.tar.bz2
3.cd protobuf-2.5.0
4../configure --prefix=/home/admin/mypython/
5.make ; make install
准備PROTO文件
message entity_attr
{
required int32 attr_id = 1; // 屬性類型標識,比如:標題屬性為 1,正文屬性為2,圖片屬性為 3,發現時間屬性為4,原始url屬性為5 ,父頁面屬性為 6;
required bytes attribute = 2; // 屬性類型描述,比如“標題”,“ 正文”,“圖片”,“發現時間”,“原始 url”,“父頁面 ”等
repeated bytes value = 3; // 屬性值,除“圖片”只保留 osskey之外,其他保留原文。考慮到文章中會保留多幅圖,所以采用repeated。
};
message entity_desc
{
required int32 entity_id = 1; // 實體類型標識,比如:新聞為 1,小說為2 。
required bytes entity_name = 2; // 實體名稱,比如:新聞主題事件關鍵詞,小說名等。
repeated entity_attr attributes = 3; // 屬性描述,格式見entity_attr。
};
當時在使用的時候,如果將字段設置為optional
並設置為0的話,那么在傳輸的過程中protobuf就會將這個字段取消掉,囧。但是JAVA就沒有這個問題。
將proto轉化為 xxx_pb2.py ,然后在你的程序里import這個py
protoc --python_out=./ ./struc_oss_pb.proto
得到struct_oss_pb_pb2.py
讀寫PROTOBUF
# coding: gbk
import struct_oss_pb_pb2
entitydesc=struct_oss_pb_pb2.entity_desc()
entitydesc.entity_id=1
entitydesc.entity_name='haha'
#create proto
entityattr=entitydesc.attributes.add() #嵌套message
entityattr.attr_id = 11
entityattr.attribute = '標題'.decode('gbk').encode('utf-8')
entityattr.value.append("title adfadf")
entity_attr_str=entityattr.SerializeToString()
print entity_attr_str
entitydesc_str=entitydesc.SerializeToString()
print entitydesc_str
當初用PROTOBUF進行RPC通信,時間長了也忘光了,最近發現網上有一個項目:
http://www.grpc.io/docs/tutorials/basic/python.html
回頭看看,再補充下