本篇次要介绍如何在Python语言中应用Google Protocol Buffer(后续都简写为PB), 包含以下几个局部:
- 为什么要应用PB?
- 装置Google PB
- 自定义.proto 文件
- 编译.proto文件
- 解析指标py文件
- 序列化和反序列化
- 更简单的Message
- 动静编译
为什么要应用PB?
PB(Protocol Buffer)是 Google 开发的用于结构化数据交换格局,作为腾讯云日志服务规范写入格局。因而用于写入日志数据前,须要将日志原始数据序列化为 PB 数据流后通过 API 写入服务端。而各个端类程序中不便操作PB格局,因而须要在端类和日志服务之间退出一层PB转化层。
当然PB格局也有本人的长处,次要是简略和快,具体测试后果参见Google序列化基准剖析
<!--more-->
装置Google PB
如果要想在Python中应用PB,须要先装置PB编译器protoc去编译你的.proto文件,装置办法如下:
下载最新的protobuf release包装置即可,以后版本为3.5.1,装置步骤如下
wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.tar.gztar xvfz protobuf-all-3.5.1.tar.gzcd protobuf-3.5.1/./configure --prefix=/usrmakemake checkmake install
check步骤全副通过即示意编译通过。
持续装置protobuf的python模块
cd ./python python setup.py build python setup.py test python setup.py install
装置实现验证protoc
命令
root@ubuntu:~# protoc --versionlibprotoc 3.5.1
protobuf的默认装置地位是 /usr/local,/usr/local/lib 不在Ubuntu零碎默认的 LD_LIBRARY_PATH 里,如果在Ubuntu零碎中configure时未指定装置门路为/usr
, 则会呈现以下谬误
protoc: error while loading shared libraries: libprotoc.so.8: cannot open shared object file: No such file or directory
能够应用ldconfig
命令解决,参考Protobuf cannot find shared libraries,这个谬误在安装包的README中有提到。当然重新安装也能够
验证Python模块是否被正确装置
import google.protobuf
在python解释器中如果下面的import没有报错,阐明装置失常。
自定义.proto 文件
首先咱们须要编写一个 proto 文件,定义咱们程序中须要解决的结构化数据,在 protobuf 的术语中,结构化数据被称为 Message。proto 文件十分相似 java 或者 C++ 语言的数据定义。proto示例文件cls.Log.proto
如下:
syntax = "proto2";package cls;message Log{ optional uint64 time = 1; // UNIX Time Format required string topic_id = 2; required string content = 3;}
.proto文件结尾是包的申明,为了帮忙避免在不同的工程中命名抵触。在Python中,包通常由目录构造决定的,所以这个.proto文件定义的包,在理论Python代码中是没有成果的。然而,依照官网的倡议是保持申明这条语句,次要作用是为了在PB的命名空间中避免名称抵触。package 名字叫做 cls,定义了一个音讯 Log,该音讯有三个成员,各个成员的含意如下:
字段名 | 类型 | 地位 | 是否必须 | 含意 |
---|---|---|---|---|
time | uint64 | body | 否 | 日志工夫,不指定,则应用服务器收到申请的工夫 |
topic_id | string | body | 是 | 日志上报到的日志主题id |
content | string | body | 是 | 日志内容 |
一个比拟好的习惯是认真对待 proto 文件的文件名。比方将命名规定定为: packageName.MessageName.proto
编译.proto文件
应用编译器protoc间接编译即可,须要指定源文件门路和指标文件门路
SRC_DIR=/tmp/src_dirDST_DIR=/tmp/dst_dirprotoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/cls.Log.proto
生成Python类就应用--python_out
选项,如果要生成C++类时应用--cpp_out
选项
解析指标py文件
在指标文件夹中生成的文件目录对应如下:
root@ubuntu:/tmp/dst_dir# tree.└── cls └── Log_pb2.py1 directory, 1 file
其中Log_pb2.py文件的内容如下(不容许编辑):
# Generated by the protocol buffer compiler. DO NOT EDIT!# source: cls.Log.protoimport sys_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))from google.protobuf import descriptor as _descriptorfrom google.protobuf import message as _messagefrom google.protobuf import reflection as _reflectionfrom google.protobuf import symbol_database as _symbol_databasefrom google.protobuf import descriptor_pb2# @@protoc_insertion_point(imports)_sym_db = _symbol_database.Default()DESCRIPTOR = _descriptor.FileDescriptor( name='cls.Log.proto', package='cls', syntax='proto2', serialized_pb=_b('\n\rcls.Log.proto\x12\x03\x63ls\"6\n\x03Log\x12\x0c\n\x04time\x18\x01 \x01(\x04\x12\x10\n\x08topic_id\x18\x02 \x02(\t\x12\x0f\n\x07\x63ontent\x18\x03 \x02(\t'))_LOG = _descriptor.Descriptor( name='Log', full_name='cls.Log', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='time', full_name='cls.Log.time', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='topic_id', full_name='cls.Log.topic_id', index=1, number=2, type=9, cpp_type=9, label=2, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='content', full_name='cls.Log.content', index=2, number=3, type=9, cpp_type=9, label=2, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=22, serialized_end=76,)DESCRIPTOR.message_types_by_name['Log'] = _LOG_sym_db.RegisterFileDescriptor(DESCRIPTOR)Log = _reflection.GeneratedProtocolMessageType('Log', (_message.Message,), dict( DESCRIPTOR = _LOG, __module__ = 'cls.Log_pb2' # @@protoc_insertion_point(class_scope:cls.Log) ))_sym_db.RegisterMessage(Log)# @@protoc_insertion_point(module_scope)
对于pb生成的py文件的源代码的解析临时搁置,能够参见附件中的材料
序列化和反序列化
#!/usr/bin/env python# -*- coding: utf-8 -*-"""Created on 1/30/18 4:23 PM@author: Chen Liang@function: pb test"""import sysreload(sys)sys.setdefaultencoding('utf-8')import Log_pb2import jsondef serialize_to_string(msg_obj): ret_str = msg_obj.SerializeToString() return ret_strdef parse_from_string(s): log = Log_pb2.Log() log.ParseFromString(s) return logif __name__ == '__main__': # serialize_to_string content_dict = {"live_id": "1239182389648923", "identify": "zxc_unique"} tencent_log = Log_pb2.Log() tencent_log.time = 1510109254 tencent_log.topic_id = "John Doe" tencent_log.content = json.dumps(content_dict) ret_s = serialize_to_string(tencent_log) print(type(ret_s)) print(ret_s) # parse_from_string log_obj = parse_from_string(ret_s) print(log_obj)
其中要害的操作在于message对象的写入和读取以及序列化函数SerializeToString
和反序列化函数ParseFromString
更简单的Message
到这里为止,咱们只给出了一个简略的上传日志的例子。在理论利用中,人们往往须要定义更加简单的 Message。咱们用“简单”这个词,不仅仅是指从个数上说有更多的 fields 或者更多类型的 fields,而是指更加简单的数据结构:
- Message嵌套
- Import Message
上面别离介绍
Message嵌套
嵌套是一个神奇的概念,一旦领有嵌套能力,音讯的表达能力就会十分弱小。具体的嵌套 Message 的例子如下
message Person { required string name = 1; required int32 id = 2; // Unique ID number for this person. optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; }
在 Message Person 中,定义了嵌套音讯 PhoneNumber,并用来定义 Person 音讯中的 phone 域。这使得人们能够定义更加简单的数据结构。
Import Message
在一个 .proto 文件中,还能够用 Import 关键字引入在其余 .proto 文件中定义的音讯,这能够称做 Import Message,或者 Dependency Message。具体的import message的例子如下
import common.header; message youMsg{ required common.info_header header = 1; required string youPrivateData = 2; }
其中 ,common.info_header
定义在common.header
包内。
Import Message 的用途次要在于提供了不便的代码管理机制,相似 C 语言中的头文件。您能够将一些专用的 Message 定义在一个 package 中,而后在别的 .proto 文件中引入该 package,进而应用其中的音讯定义。
Google Protocol Buffer 能够很好地反对嵌套 Message 和引入 Message,从而让定义简单的数据结构的工作变得十分轻松愉快。
动静编译
个别状况下,应用 Protobuf 的人们都会先写好 .proto 文件,再用 Protobuf 编译器生成目标语言所须要的源代码文件。将这些生成的代码和应用程序一起编译。
可是在某且状况下,人们无奈事后晓得 .proto 文件,他们须要动静解决一些未知的 .proto 文件。比方一个通用的音讯转发中间件,它不可能预知须要解决怎么的音讯。这须要动静编译 .proto 文件,并应用其中的 Message。
具体解释参见:Google Protocol Buffer 的应用和原理
参考:
- https://developers.google.com...
- https://developers.google.com...
- http://hzy3774.iteye.com/blog...
- https://github.com/google/pro...
- https://github.com/google/pro...
- https://blog.csdn.net/losophy...
- https://www.ibm.com/developer...
- https://github.com/google/pro...
- https://github.com/google/pro...
- Python Google Protocol Buffer: https://developers.google.com...
记得帮我点赞哦!
精心整顿了计算机各个方向的从入门、进阶、实战的视频课程和电子书,依照目录正当分类,总能找到你须要的学习材料,还在等什么?快去关注下载吧!!!
朝思暮想,必有回响,小伙伴们帮我点个赞吧,非常感谢。
我是职场亮哥,YY高级软件工程师、四年工作教训,回绝咸鱼争当龙头的斜杠程序员。听我说,提高多,程序人生一把梭
如果有幸能帮到你,请帮我点个【赞】,给个关注,如果能顺带评论给个激励,将不胜感激。
职场亮哥文章列表:更多文章
自己所有文章、答复都与版权保护平台有单干,著作权归职场亮哥所有,未经受权,转载必究!