Python uses protobuf

Source: Internet
Author: User

1. Install the PROTOBUF compiler

./configure--prefix=dist; Make make install; Configuring the Bin Path

2. Into the extracted Python directory

Reference Readme.txt,python setup.py Install

3. Use

Message Rowproto {
required uint32 null_map = 1;
Repeated string column = 2;
}

Message Tableproto {
repeated string column = 1;
Repeated string row = 2;
}

Compile

Protoc--python_out=/data/home/./dataservice.proto
Get dataservice_pb2.py

Instance

Import sys
import DATASERVICE_PB2

#create proto
row = dataservice_pb2. Rowproto ()
row.null_map = 1
row.column.append ("Wang")
row.column.append ("female")
Row_str=row. Serializetostring ()
print row_str
table = dataservice_pb2. Tableproto ()
table.column.append ("name")
table.column.append ("gender")
Table.row.append (ROW_STR)
table_str = table. Serializetostring ()

#process proto
Table_proto = dataservice_pb2. Tableproto ()
Table_proto. Parsefromstring (TABLE_STR)
print "column:"
print table_proto.column

row_str = table_proto.row[0]
Row_proto = dataservice_pb2. Rowproto ()
Row_proto. Parsefromstring (Row_str.encode (' UTF8 '))
print "Row1:"
print Row_proto.column

Read files

Import sys
import dataservice_pb2
  f = open ("table", ' RB ',)
  Table_proto = Dataservice_pb2. Tableproto ()
  Table_proto. Parsefromstring (F.read ())
  print Table_proto.column
  #print table_proto.row for
  row in Table_proto.row:
    Row_proto = dataservice_pb2. Rowproto ()
    Row_proto. Parsefromstring (Row.encode (' Utf-8 '))
    print Row_proto.column
  f.close ()


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.