python post protobuf
本文主要讲述如何使用Python发送protobuf数据。
安装protobuf
tar zxvf protobuf-2.6.1.tar.gz cd protobuf-2.6.1 ./configure make make install
安装成功。
// 查看protoc版本 protoc --version
python安装protobuf
cd protobuf-2.6.1/python python setup.py build python setup.py install
环境搭建完毕,下面给个demo。
创建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; } }
编译proto文件
protoc -I=. --python_out=. ./my_bidding.proto
编译成功,会产生my_bidding_pb2.py。
编写Python脚本
# 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()