当前位置:   article > 正文

python中使用 protocol buffer(Protobuf)_python 获取protobuf依赖版本

python 获取protobuf依赖版本

项目中引入proto的依赖

【两种方法】:
方法1、 官网下载对应的语言包,https://github.com/protocolbuffers/protobuf/releases 

这里选择python下载 https://github.com/protocolbuffers/protobuf/releases/download/v3.5.1/protobuf-python-3.5.1.tar.gz

解压后进入python-protobuf-3.5.1/python目录,执行python3 setup.py install


方法2 、【推荐】命令行执行pip3 install protobuf,此时会下载最新的protobuf版本,如果下载的版本与本地安装的proto命令版本不一致,有可能导致异常,所以此时最好指定要下载的版本号:pip3 install protobuf==3.5.1

【注意】

  • 上面的安装方式是全局安装,安装成功后对应的依赖包都会被安装到对应的site-packages目录下,比如/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages使用IDE开发时,如PyCharm,绑定interpreter时要注意勾选inherit global site-packages,这样项目才能使用全局依赖中的所有包
  • 如果只是为当前项目安装依赖包可以不勾选inherit global site-packages,然后进入当前项目依赖的pip目录,即Location指定的路径下,执行./bin/pip install protobuf==3.5.1来安装需要的依赖包

准备proto文件

  • proto示例文件参考[Protocol Buffer学习笔记(Java&NodeJS)]
    (https://www.jianshu.com/p/55f4b4b22dd2)
  • python同时支持proto2和proto3,所以如果基于proto3,这里注意去掉其中的requiredoptional,因为这里要求语法严格遵循proto3,不能在属性前出现requiredoptional,同时文件顶端要明确syntax = "proto3";

生成proto对应的python文件

  • 命令行执行
    protoc --python_out=. OTIpcDef.proto
  • 此时会在当前目录下生成OTIpcDef_pb2.py,将该文件拷贝到项目中,比如放到项目根目录的proto目录下

python中使用protobuf

  1. from proto import OTIpcDef_pb2
  2. otIpcList = OTIpcDef_pb2.OTIpcList()
  3. # list类型数据创建方式
  4. otIpc = otIpcList.otpic.add()
  5. otIpc.CompanyId = "companyId"
  6. otIpc.Source = "Source"
  7. otIpc.IPCType = OTIpcDef_pb2.baseInfoCompany
  8. # list类型数据创建方式
  9. baseInfoCompany = otIpc.baseInfoCompany.add()
  10. # print(type(baseInfoCompany))
  11. baseInfoCompany.Address = 110011
  12. baseInfoCompany.CompanyId = "companyId"
  13. baseInfoCompany.CompanyName = "companyName中文"
  14. baseInfoCompany.Identifier = "identifier"
  15. baseInfoCompany.BusinessScope = "BusinessScope"
  16. baseInfoCompany.ContactAddress = "ContactAddress"
  17. baseInfoCompany.EconomicType = "EconomicType"
  18. baseInfoCompany.RegCapital = "RegCapital"
  19. baseInfoCompany.LegalName = "LegalName"
  20. baseInfoCompany.LegalID = "LegalID"
  21. baseInfoCompany.LegalPhone = "LegalPhone"
  22. baseInfoCompany.State = 0
  23. baseInfoCompany.Flag = 1
  24. baseInfoCompany.UpdateTime = 20180226121212
  25. otIpc2 = otIpcList.otpic.add()
  26. otIpc2.CompanyId = "companyId"
  27. otIpc2.Source = "Source"
  28. otIpc2.IPCType = OTIpcDef_pb2.baseInfoCompanyStat
  29. baseInfoCompanyStat = otIpc2.baseInfoCompanyStat.add()
  30. baseInfoCompanyStat.CompanyId = "companyId"
  31. baseInfoCompanyStat.DriverNum = 10
  32. baseInfoCompanyStat.Flag = 0
  33. baseInfoCompanyStat.UpdateTime = 20180226121212
  34. baseInfoCompanyStat.VehicleNum = 5
  35. print("============================================")
  36. # print(otIpc)
  37. print(otIpcList)
  38. print("============================================")
  39. # 序列化
  40. b = otIpcList.SerializeToString()
  41. # 打印二进制数据
  42. print(b)
  43. print("============================================")
  44. otIpcList2 = OTIpcDef_pb2.OTIpcList()
  45. # 反序列化
  46. otIpcList2.ParseFromString(b)
  47. print(otIpcList2)

 

python中使用protobuf 实例2

data.proto:

  1. syntax = "proto3";
  2. package protobuf;
  3. message SendData {
  4. int32 request_type = 1;
  5. int32 tool_type = 2;
  6. string data = 3;
  7. }
  8. message RevcData {
  9. int32 status = 1;
  10. string error_msg = 2;
  11. int32 request_type = 3;
  12. int32 tool_type = 4;
  13. string data = 5;
  14. }

执行命令: 

protoc --python_out=. data.proto

得到 data_pb2.py:

  1. # -*- coding: utf-8 -*-
  2. # Generated by the protocol buffer compiler. DO NOT EDIT!
  3. # source: data.proto
  4. import sys
  5. _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
  6. from google.protobuf import descriptor as _descriptor
  7. from google.protobuf import message as _message
  8. from google.protobuf import reflection as _reflection
  9. from google.protobuf import symbol_database as _symbol_database
  10. # @@protoc_insertion_point(imports)
  11. _sym_db = _symbol_database.Default()
  12. DESCRIPTOR = _descriptor.FileDescriptor(
  13. name='data.proto',
  14. package='protobuf',
  15. syntax='proto3',
  16. serialized_options=None,
  17. serialized_pb=_b('\n\ndata.proto\x12\x08protobuf\"A\n\x08SendData\x12\x14\n\x0crequest_type\x18\x01 \x01(\x05\x12\x11\n\ttool_type\x18\x02 \x01(\x05\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\t\"d\n\x08RevcData\x12\x0e\n\x06status\x18\x01 \x01(\x05\x12\x11\n\terror_msg\x18\x02 \x01(\t\x12\x14\n\x0crequest_type\x18\x03 \x01(\x05\x12\x11\n\ttool_type\x18\x04 \x01(\x05\x12\x0c\n\x04\x64\x61ta\x18\x05 \x01(\tb\x06proto3')
  18. )
  19. _SENDDATA = _descriptor.Descriptor(
  20. name='SendData',
  21. full_name='protobuf.SendData',
  22. filename=None,
  23. file=DESCRIPTOR,
  24. containing_type=None,
  25. fields=[
  26. _descriptor.FieldDescriptor(
  27. name='request_type', full_name='protobuf.SendData.request_type', index=0,
  28. number=1, type=5, cpp_type=1, label=1,
  29. has_default_value=False, default_value=0,
  30. message_type=None, enum_type=None, containing_type=None,
  31. is_extension=False, extension_scope=None,
  32. serialized_options=None, file=DESCRIPTOR),
  33. _descriptor.FieldDescriptor(
  34. name='tool_type', full_name='protobuf.SendData.tool_type', index=1,
  35. number=2, type=5, cpp_type=1, label=1,
  36. has_default_value=False, default_value=0,
  37. message_type=None, enum_type=None, containing_type=None,
  38. is_extension=False, extension_scope=None,
  39. serialized_options=None, file=DESCRIPTOR),
  40. _descriptor.FieldDescriptor(
  41. name='data', full_name='protobuf.SendData.data', index=2,
  42. number=3, type=9, cpp_type=9, label=1,
  43. has_default_value=False, default_value=_b("").decode('utf-8'),
  44. message_type=None, enum_type=None, containing_type=None,
  45. is_extension=False, extension_scope=None,
  46. serialized_options=None, file=DESCRIPTOR),
  47. ],
  48. extensions=[
  49. ],
  50. nested_types=[],
  51. enum_types=[
  52. ],
  53. serialized_options=None,
  54. is_extendable=False,
  55. syntax='proto3',
  56. extension_ranges=[],
  57. oneofs=[
  58. ],
  59. serialized_start=24,
  60. serialized_end=89,
  61. )
  62. _REVCDATA = _descriptor.Descriptor(
  63. name='RevcData',
  64. full_name='protobuf.RevcData',
  65. filename=None,
  66. file=DESCRIPTOR,
  67. containing_type=None,
  68. fields=[
  69. _descriptor.FieldDescriptor(
  70. name='status', full_name='protobuf.RevcData.status', index=0,
  71. number=1, type=5, cpp_type=1, label=1,
  72. has_default_value=False, default_value=0,
  73. message_type=None, enum_type=None, containing_type=None,
  74. is_extension=False, extension_scope=None,
  75. serialized_options=None, file=DESCRIPTOR),
  76. _descriptor.FieldDescriptor(
  77. name='error_msg', full_name='protobuf.RevcData.error_msg', index=1,
  78. number=2, type=9, cpp_type=9, label=1,
  79. has_default_value=False, default_value=_b("").decode('utf-8'),
  80. message_type=None, enum_type=None, containing_type=None,
  81. is_extension=False, extension_scope=None,
  82. serialized_options=None, file=DESCRIPTOR),
  83. _descriptor.FieldDescriptor(
  84. name='request_type', full_name='protobuf.RevcData.request_type', index=2,
  85. number=3, type=5, cpp_type=1, label=1,
  86. has_default_value=False, default_value=0,
  87. message_type=None, enum_type=None, containing_type=None,
  88. is_extension=False, extension_scope=None,
  89. serialized_options=None, file=DESCRIPTOR),
  90. _descriptor.FieldDescriptor(
  91. name='tool_type', full_name='protobuf.RevcData.tool_type', index=3,
  92. number=4, type=5, cpp_type=1, label=1,
  93. has_default_value=False, default_value=0,
  94. message_type=None, enum_type=None, containing_type=None,
  95. is_extension=False, extension_scope=None,
  96. serialized_options=None, file=DESCRIPTOR),
  97. _descriptor.FieldDescriptor(
  98. name='data', full_name='protobuf.RevcData.data', index=4,
  99. number=5, type=9, cpp_type=9, label=1,
  100. has_default_value=False, default_value=_b("").decode('utf-8'),
  101. message_type=None, enum_type=None, containing_type=None,
  102. is_extension=False, extension_scope=None,
  103. serialized_options=None, file=DESCRIPTOR),
  104. ],
  105. extensions=[
  106. ],
  107. nested_types=[],
  108. enum_types=[
  109. ],
  110. serialized_options=None,
  111. is_extendable=False,
  112. syntax='proto3',
  113. extension_ranges=[],
  114. oneofs=[
  115. ],
  116. serialized_start=91,
  117. serialized_end=191,
  118. )
  119. DESCRIPTOR.message_types_by_name['SendData'] = _SENDDATA
  120. DESCRIPTOR.message_types_by_name['RevcData'] = _REVCDATA
  121. _sym_db.RegisterFileDescriptor(DESCRIPTOR)
  122. SendData = _reflection.GeneratedProtocolMessageType('SendData', (_message.Message,), {
  123. 'DESCRIPTOR' : _SENDDATA,
  124. '__module__' : 'data_pb2'
  125. # @@protoc_insertion_point(class_scope:protobuf.SendData)
  126. })
  127. _sym_db.RegisterMessage(SendData)
  128. RevcData = _reflection.GeneratedProtocolMessageType('RevcData', (_message.Message,), {
  129. 'DESCRIPTOR' : _REVCDATA,
  130. '__module__' : 'data_pb2'
  131. # @@protoc_insertion_point(class_scope:protobuf.RevcData)
  132. })
  133. _sym_db.RegisterMessage(RevcData)
  134. # @@protoc_insertion_point(module_scope)

测试文件 send.py:

  1. # -*- coding: utf-8 -*-
  2. import data_pb2
  3. import json
  4. if __name__ == "__main__":
  5. test_dict = {
  6. "test1":1,
  7. "test2":2
  8. }
  9. sendData = data_pb2.SendData()
  10. sendData.request_type = 1
  11. sendData.tool_type = 1
  12. sendData.data = json.dumps(test_dict)
  13. print("============================================")
  14. # print(otIpc)
  15. print(sendData)
  16. print("============================================")
  17. # 序列化
  18. b = sendData.SerializeToString()
  19. # 打印二进制数据
  20. print(b)
  21. print("============================================")
  22. sendData2 = data_pb2.SendData()
  23. # 反序列化
  24. sendData2.ParseFromString(b)
  25. print(sendData2)

执行结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/901002
推荐阅读
相关标签
  

闽ICP备14008679号