PYTHON讀寫PB


PYTHON讀寫PB

前期准備

准備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

回頭看看,再補充下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM