Python使用protobuf序列化和反序列化的實現
protobuf是一種二進制的序列化格式,相對于json來說體積更小,傳輸更快。
安裝protobuf安裝protobuf的目的主要用來將proto文件編譯成python、c、Java可調用的接口。
# 如果gcc版本較低,需要升級gccwget https://main.qcloudimg.com/raw/d7810aaf8b3073fbbc9d4049c21532aa/protobuf-2.6.1.tar.gztar -zxvf protobuf-2.6.1.tar.gz -C /usr/local/ && cd /usr/local/protobuf-2.6.1./configure make && make install# 可以在/etc/profile或者~/.bash_profile末尾設置永久有效export PATH=$PATH:/usr/local/protobuf-2.6.1/bin
使用下面命令查看是否安裝成功。
[root@CodeOnTheRoad ~]# protoc --versionlibprotoc 2.6.1構建python接口
創建cls.proto文件,定義序列化結構:
package cls;message Log{ message Content {required string key = 1; // 每組字段的 keyrequired string value = 2; // 每組字段的 value } required int64 time = 1; // 時間戳,UNIX時間格式 repeated Content contents = 2; // 一條日志里的多個kv組合}message LogTag{ required string key = 1; required string value = 2;}message LogGroup{ repeated Log logs= 1; // 多條日志合成的日志數組 optional string contextFlow = 2; // 目前暫無效用 optional string filename = 3; // 日志文件名 optional string source = 4; // 日志來源,一般使用機器IP repeated LogTag logTags = 5;}message LogGroupList{ repeated LogGroup logGroupList = 1; // 日志組列表}
只用下面命令將proto文件轉換為python可調用的接口。
protoc cls.proto --python_out=./
執行完后,在此目錄下生成cls_pb2.py。
序列化import cls_pb2 as clsimport time# 構建protoBuf日志內容LogLogGroupList = cls.LogGroupList()LogGroup = LogLogGroupList.logGroupList.add()LogGroup.contextFlow = '1'LogGroup.filename = 'python.log'LogGroup.source = 'localhost'LogTag = LogGroup.logTags.add()LogTag.key = 'key'LogTag.value = 'value'Log = LogGroup.logs.add()Log.time = int(round(time.time() * 1000000))Content = Log.contents.add()Content.key = 'Hello'Content.value = 'World'print(LogLogGroupList)# 序列化data = LogLogGroupList.SerializeToString()print(data)
其實就是講一個protobuf的結構文本序列化成了二進制的形式。
反序列化反序列化就是將二進制轉換成protobuf結構。
# 反序列化LogLogGroupList = cls.LogGroupList()LogLogGroupList.ParseFromString(data)print(LogLogGroupList)
運行結果
上面序列化和反序列化代碼結果運行如下:
到此這篇關于Python使用protobuf序列化和反序列化的實現的文章就介紹到這了,更多相關Python 序列化和反序列化內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
