導航:首頁 > 編程語言 > 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例子相關的資料

熱點內容
安卓外放聲音怎麼解決 瀏覽:194
脈脈app干什麼用的 瀏覽:357
拽姐是哪個app 瀏覽:858
雲伺服器刪除了還有嗎 瀏覽:232
macbook可以用單片機嘛 瀏覽:307
南陽php招聘 瀏覽:814
去哪裡找按摩師很漂亮的app 瀏覽:818
86x99用簡便演算法計算 瀏覽:830
php截圖flash 瀏覽:274
卸載聯想app哪個好 瀏覽:720
php文字轉圖片 瀏覽:332
豆客後台怎麼加密碼 瀏覽:575
jpg轉換pdf破解版 瀏覽:979
php基礎書籍推薦 瀏覽:779
伺服器與外網不通如何驗證 瀏覽:353
電子版是不是就是文件夾 瀏覽:52
游戲屬性文件加密 瀏覽:464
如何讓安卓手機桌面圖標下移 瀏覽:530
ubuntuphp5環境搭建 瀏覽:101
賭癮解壓視頻 瀏覽:919