This paper describes how to send data protobuf use Python.
Installation protobuf
tar zxvf protobuf 2.6 . 1 . tar gz cd protobuf-2.6.1 ./configure make make install
Successful installation.
// Check protoc version protoc --version
python installation protobuf
cd protobuf- 2.6 . 1 / python python setup.py build python setup.py install
Environment set up is completed, the following give a demo.
Creating my_bidding.proto
package tutorial; message Person { required string name = 1; optional int32 age = 2; repeated BankCard bankcard = 3; message BankCard { required string id = 1; } optional RealEstate estate = 4; message RealEstate { required string address = 1; optional int32 value = 2; } optional bool isSingle = 5; optional SexualOrientation orientation = 6; enum SexualOrientation { ManOnly = 1 ; WomanOnly = 2; BiSexual = 3; } }
Compile proto file
protoc -I=. --python_out=. ./my_bidding.proto
Compile successful, will produce my_bidding_pb2.py.
Python scripting
# python2 # coding = utf-8 import my_bidding_pb2 import httplib person = my_bidding_pb2.Person() person.name = 'logan' person.age = 25 person.isSingle = False person.orientation = 3 bankcard1 = person.bankcard.add() bankcard1.id = '100' bankcard2 = person.bankcard.add() bankcard2.id = '101' real_estate = person.estate real_estate.address = 'beijing' real_estate.value = 1000 print person data = person.SerializeToString() CONTENT_TYPE = "application/octet-stream" CONTENT_TYPE_HEADER = "Content-type" conn = httplib.HTTPConnection('sever_host', 'server_port') conn.request('POST', 'server_path', data, {CONTENT_TYPE_HEADER: CONTENT_TYPE}) response = conn.getresponse() print response print response.status print response.read()
Reproduced in: https: //www.cnblogs.com/gattaca/p/7240763.html