导航:首页 > 编程语言 > protobufpython例子

protobufpython例子

发布时间:2022-08-28 00:30:03

‘壹’ 求助protobuf在python中创建一个对象为何要占用那么多内存

例如我定义一个message
message TestMes {
string test = 1;
}
我只定义了一个string。然后我在python程序中用它,作为对比,也用了python自己的string

@profile
def addstring():
sss = []
for i in range(1000):
info = "dsdf_sdf" + str(i)
sss.append(info)

@profile
def addtestmes():
sss = []
for i in range(1000):
test_mes = TestMes()
sss.append(test_mes)

执行命令
python -m memory_profiler test.py

打印结果是
Filename: testing.py

Line # Mem usage Increment Line Contents
================================================
345 19.211 MiB 0.000 MiB @profile
346 def addstring():
347 19.211 MiB 0.000 MiB sss = []
348 19.219 MiB 0.008 MiB for i in range(1000):
349 19.219 MiB 0.000 MiB info = "$sdf" + str(i)
350 19.219 MiB 0.000 MiB sss.append(info)
351 19.219 MiB 0.000 MiB print len(sss)
352 19.219 MiB 0.000 MiB print sss[999]

Filename: testing.py

Line # Mem usage Increment Line Contents
================================================
354 19.219 MiB 0.000 MiB @profile
355 def addtestmes():
356 19.219 MiB 0.000 MiB sss = []
357 19.977 MiB 0.758 MiB for i in range(1000):
358 19.977 MiB 0.000 MiB test_mes = TestMes()
359 19.977 MiB 0.000 MiB sss.append(test_mes)
我用python string的只用了0.008M内存,而用protobuf message的,用了0.758M内存。 需要保持很多信息

‘贰’ windows protobuf怎么用

protobuf win下安装与使用

‘叁’ 如何编译安装protobuf极其python版本

由于google连不上,直接pip安装很多情况下会失败,这时候就需要手工编译安装。

下面以2.4.1为例。

首先自己设法下载一个源码包:protobuf-2.4.1.tar.bz2,假设放到/data目录下

1.安装protobuf

[plain]view plain

‘肆’ python怎么经过protobuf完成rpc

客户方像挪用当地办法同样去挪用长途接口办法,RPC 结构供给接口的署理完成,理论的挪用将拜托给署理RpcProxy
。署理封装挪用资讯并将挪用转交给RpcInvoker 去理论履行。在客户真个RpcInvoker 经过衔接器RpcConnector
去保持与效劳端的通道RpcChannel,并运用RpcProtocol
履行协定编码(encode)并将编码后的恳求音讯经过通道发送给效劳方。RPC 效劳端接纳器 RpcAcceptor
接纳客户真个挪用恳求,一样运用RpcProtocol 履行协定解码(decode)。解码后的挪用资讯传送给RpcProcessor
去掌握处置挪用进程,末了再拜托挪用给RpcInvoker 去理论履行并前往挪用后果。

protobuf
rpc在下面组件中首要表演RpcProtocol的人物,使得咱们省去了协定的描绘,而且protobuf协定在编码和时间效力都是上十分高效的,这也是许多公司选用protobuf作为数值序列化和通讯协议的起因。一起protobuf
rpc界说了一个笼统的rpc结构,以下图所示:

RpcServiceStub和RpcService类是protobuf编译器依据proto界说天生的类,RpcService界说了效劳端表露给客户真个函数接口,详细完成需求用户本人担当这个类来完成。RpcServiceStub界说了效劳端表露函数的描绘,并将客户端对RpcServiceStub中函数的挪用同一转换到挪用RpcChannel中的CallMethod办法,CallMethod经过RpcServiceStub传过去的函数描绘符和函数参数对该次rpc挪用停止encode,最后经过RpcConnecor发送给效劳方。自己以客户端相反的进程最后挪用RpcSerivice中界说的函数。现实上,protobuf

rpc的结构仅仅RpcChannel中界说了空的CallMethod,以是详细怎么样停止encode和挪用RpcConnector都要本人完成。RpcConnector在protobuf中没有界说,以是这个完结由用户本人完成,它的效果那是收发rpc音讯包。在效劳端,RpcChannel经过挪用RpcService中的CallMethod来详细挪用RpcService中表露给客户真个函数。

引见了这么多,关于怎样用protobuf rpc来完成一个rpc确定仍是一头雾水吧,下面就用protobuf rpc来完成一个简略的python版rpc demo吧。

下面间接给出demo描绘PRC的proto文件,至于proto文件的编写规定能够参考protobuf官网。

common.proto文件:

package game;

message RequestMessage
{
required string message = 1;
}

message ResponseMessage
{
required string message = 1;
}

game_service.proto文件:

package game;

import "common.proto";
option py_generic_services = true;

service GameService
{
rpc connect_server(RequestMessage) returns(RequestMessage);
}

common.proto文件描绘了RPC中收发的音讯;game_service.proto描绘了效劳器导出的connect_server函数,该函数承受RequestMessage目标作为参数,并前往RequestMessage目标。在运用PRC协定时,必需加之option
py_generic_services =
true;可选项,要否则编译器不会天生蕴含connect_server函数的GameService描绘。

运用编译器protoc编译proto文件,详细号令为:
protoc.exe --python_out=. game_service.proto
编译后天生的文件为game_service_pb2.py,该文件首要是完成了GameService和GameService_Stub类。GameService_Stub类用于客户端挪用者来挪用GameService的效劳。
后面曾经说了,在客户端,RpcChannel只完成了一个空的CallMethod,以是需求担当RpcChannel从新这个函数来encode音讯和发送音讯。在效劳端RpcChannel需求挪用CallMethod来挪用Service中的函数。详细完成以下:

class MyRpcChannel(service.RpcChannel):
def __init__(self, rpc_service, conn):
super(MyRpcChannel, self).__init__()
self.logger = LogManager.get_logger("MyRpcChannel")

def CallMethod(self, method_descriptor, rpc_controller, request, response_class, done):
""""protol buffer rpc 需求的函数,用来发送rpc挪用"""
self.logger.info('CallMethod')
cmd_index = method_descriptor.index
assert(cmd_index < 65535)
data = request.SerializeToString()
total_len = len(data) + 2
self.conn.send_data(''.join([pack('<I', total_len), pack('<H', cmd_index), data]))

def from_request(self):
""""从收集剖析出一个完好的恳求以后调的函数"""
index_data = self.rpc_request.data[0:2]
cmd_index = unpack('<H', index_data)[0]
rpc_service = self.rpc_service
s_descriptor = rpc_service.GetDescriptor()
method = s_descriptor.methods[cmd_index]
try:
request = rpc_service.GetRequestClass(method)()
serialized = self.rpc_request.data[2:]
request.ParseFromString(serialized)
rpc_service.CallMethod(method, self.controller, request, None)
except:
self.logger.error("Call rpc method failed!")
self.logger.log_last_except()
return True

末了那是担当GameService,并完成connect_server函数了。

class GameService(game_service_pb2.GameService):
def __init__(self):
self.logger = LogManager.get_logger("GameService")

def connect_server(self, rpc_controller, request, callback):
self.logger.info('%s', request.message)

至于用于收集收发音讯的RpcConnector,可使用python的asyncore库完成,详细完成在这就不评论了。

从下面的完成来看,protobuf rpc的完成首要囊括编写proto文件并编译天生对应的service_pb2文件,担当RpcChannel并完成CallMethod和挪用Service的CallMethod,担当Service来完成表露给客户真个函数。

‘伍’ 如何使用Python中的buffer

1.需要安装Protocol Buffer

直接:apt-get install protobuf-compiler

安装完毕后,进入解压目录的python目录,执行python setup.py install;安装python的protobuf库即可。

2.可以查询到它的大致用法

pijing@ubuntu:~/protobuffer$ protoc -h
Usage: protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
-IPATH, --proto_path=PATH Specify the directory in which to search for
imports. May be specified multiple times;
directories will be searched in order. If not
given, the current working directory is used.
--version Show version info and exit.
-h, --help Show this text and exit.
--encode=MESSAGE_TYPE Read a text-format message of the given type
from standard input and write it in binary
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode=MESSAGE_TYPE Read a binary message of the given type from
standard input and write it in text format
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode_raw Read an arbitrary protocol message from
standard input and write the raw tag/value
pairs in text format to standard output. No
PROTO_FILES should be given when using this
flag.
-oFILE, Writes a FileDescriptorSet (a protocol buffer,
--descriptor_set_out=FILE defined in descriptor.proto) containing all of
the input files to FILE.
--include_imports When using --descriptor_set_out, also include
all dependencies of the input files in the
set, so that the set is self-contained.
--include_source_info When using --descriptor_set_out, do not strip
SourceCodeInfo from the FileDescriptorProto.
This results in vastly larger descriptors that
include information about the original
location of each decl in the source file as
well as surrounding comments.
--error_format=FORMAT Set the format in which to print errors.
FORMAT may be 'gcc' (the default) or 'msvs'
(Microsoft Visual Studio format).
--plugin=EXECUTABLE Specifies a plugin executable to use.
Normally, protoc searches the PATH for
plugins, but you may specify additional
executables not in the path using this flag.
Additionally, EXECUTABLE may be of the form
NAME=PATH, in which case the given plugin name
is mapped to the given executable even if
the executable's own name differs.
--cpp_out=OUT_DIR Generate C++ header and source.
--java_out=OUT_DIR Generate Java source file.
--python_out=OUT_DIR Generate Python source file.

3.简单使用一下

首先定义proto文件,my.proto
{
optional int32 id=1;
optional string testname=2;
}

然后,执行命令:

protoc --python_out=./ ./my.proto

得到my_pb2.py文件

最后,在当前目录下新建一个test.py文件夹,写入测试的脚本,包括序列化和反序列化代码:


‘陆’ 如何用python运行protobuf编译器

http://blog.csdn.net/dark_spider/article/details/28390183
希望回答能给你带来帮助
如果满意,请采纳,如有疑问,可继续追问。

‘柒’ 怎么样编写Protobuf的.proto文件

ProtoBuf java 包编译ProtoBuf的官方下载包并不包含jar文件,需要用户自己configure/make….来自行编译。由于Windows上没有编译环境,就用了一个笨一点方法处理了。
分别下载:
protobuf-2.4.1.zip ProtoBuf的源文件(包含了C++/Java/Python)的源文件
protoc-2.4.1-win32.zip 已经编译过的用于Windows平台的protoc命令(该命令用于将.proto文件转化为Java或C++源文件)。

分别解析这两个文件,你可以在protoc-2.4.1-win32.zip解压后的文件中找到一个protoc.exe文件,将其到protobuf-2.4.1/src目录下,然后进入protobuf-2.4.1/java,执行:
mvn install

‘捌’ 如何用python把protobuf转化json

直接利用python提供的json包,在django model的定义中增加一个方法toJSON,利用django model 能访问 _meta.fields 得到相关属性而得到,例子如下:
class Category(models.Model):
autoid = models.AutoField(primary_key=True)
email=models.CharField(max_length=150,blank=False)
comtype=models.CharField(max_length=20,blank=False)
catname=models.CharField(max_length=150,blank=False)

def __unicode__(self):
return '%s' % (self.catname)

def toJSON(self):
import json
return json.mps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
然后用django查出数据,并转换成json,代码如下:
row=models.Category.objects.get(autoid=23)
print row.toJSON()

‘玖’ python中怎么将对象赋值给protobuf repeated 字段

python protobuf序列化repeated运用

下面是proto描述文件的定义
message Person {
required string name = 1;
required int32 id = 2;
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 AddressBook {
repeated Person person = 1;
}
在python中利用google.protobuf序列化数据进行通讯的时候,一定会遇到repeated的数据如何去创建
在这里我给大家分享一下:
import addressbook_pb2
person = addressbook_pb2.Person()
person.id = 1234
person.name = "John Doe"
person.email = "[email protected]"
phone = person.phone.add()
phone.number = "555-4321"
phone.type = addressbook_pb2.Person.HOME
person.no_such_field = 1
person.id = "1234"
请注意加红的一行代码,这就是重点,如果想再添加一个的话phone2 = person.phone.add()即可,然后给phone2赋值。

阅读全文

与protobufpython例子相关的资料

热点内容
卸载联想app哪个好 浏览:719
php文字转图片 浏览:328
豆客后台怎么加密码 浏览:574
jpg转换pdf破解版 浏览:978
php基础书籍推荐 浏览:775
服务器与外网不通如何验证 浏览:351
电子版是不是就是文件夹 浏览:50
游戏属性文件加密 浏览:462
如何让安卓手机桌面图标下移 浏览:528
ubuntuphp5环境搭建 浏览:99
赌瘾解压视频 浏览:917
晋城移动dns服务器地址 浏览:294
php开源文库系统 浏览:134
android记事本源码 浏览:407
安卓11小游戏怎么玩法 浏览:190
gif有损压缩 浏览:937
windows下安装linux命令操作 浏览:844
米家app怎么设置进门亮灯 浏览:652
任我行服务器为什么会影响截图 浏览:296
安卓留言板怎么删除 浏览:18