店播爬取Python脚本

descriptor.py 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Descriptors essentially contain exactly the information found in a .proto
  31. file, in types that make this information accessible in Python.
  32. """
  33. __author__ = 'robinson@google.com (Will Robinson)'
  34. import threading
  35. import warnings
  36. import six
  37. from google.protobuf.internal import api_implementation
  38. _USE_C_DESCRIPTORS = False
  39. if api_implementation.Type() == 'cpp':
  40. # Used by MakeDescriptor in cpp mode
  41. import binascii
  42. import os
  43. from google.protobuf.pyext import _message
  44. _USE_C_DESCRIPTORS = True
  45. class Error(Exception):
  46. """Base error for this module."""
  47. class TypeTransformationError(Error):
  48. """Error transforming between python proto type and corresponding C++ type."""
  49. if _USE_C_DESCRIPTORS:
  50. # This metaclass allows to override the behavior of code like
  51. # isinstance(my_descriptor, FieldDescriptor)
  52. # and make it return True when the descriptor is an instance of the extension
  53. # type written in C++.
  54. class DescriptorMetaclass(type):
  55. def __instancecheck__(cls, obj):
  56. if super(DescriptorMetaclass, cls).__instancecheck__(obj):
  57. return True
  58. if isinstance(obj, cls._C_DESCRIPTOR_CLASS):
  59. return True
  60. return False
  61. else:
  62. # The standard metaclass; nothing changes.
  63. DescriptorMetaclass = type
  64. class _Lock(object):
  65. """Wrapper class of threading.Lock(), which is allowed by 'with'."""
  66. def __new__(cls):
  67. self = object.__new__(cls)
  68. self._lock = threading.Lock() # pylint: disable=protected-access
  69. return self
  70. def __enter__(self):
  71. self._lock.acquire()
  72. def __exit__(self, exc_type, exc_value, exc_tb):
  73. self._lock.release()
  74. _lock = threading.Lock()
  75. def _Deprecated(name):
  76. if _Deprecated.count > 0:
  77. _Deprecated.count -= 1
  78. warnings.warn(
  79. 'Call to deprecated create function %s(). Note: Create unlinked '
  80. 'descriptors is going to go away. Please use get/find descriptors from '
  81. 'generated code or query the descriptor_pool.'
  82. % name,
  83. category=DeprecationWarning, stacklevel=3)
  84. # Deprecated warnings will print 100 times at most which should be enough for
  85. # users to notice and do not cause timeout.
  86. _Deprecated.count = 100
  87. _internal_create_key = object()
  88. class DescriptorBase(six.with_metaclass(DescriptorMetaclass)):
  89. """Descriptors base class.
  90. This class is the base of all descriptor classes. It provides common options
  91. related functionality.
  92. Attributes:
  93. has_options: True if the descriptor has non-default options. Usually it
  94. is not necessary to read this -- just call GetOptions() which will
  95. happily return the default instance. However, it's sometimes useful
  96. for efficiency, and also useful inside the protobuf implementation to
  97. avoid some bootstrapping issues.
  98. """
  99. if _USE_C_DESCRIPTORS:
  100. # The class, or tuple of classes, that are considered as "virtual
  101. # subclasses" of this descriptor class.
  102. _C_DESCRIPTOR_CLASS = ()
  103. def __init__(self, options, serialized_options, options_class_name):
  104. """Initialize the descriptor given its options message and the name of the
  105. class of the options message. The name of the class is required in case
  106. the options message is None and has to be created.
  107. """
  108. self._options = options
  109. self._options_class_name = options_class_name
  110. self._serialized_options = serialized_options
  111. # Does this descriptor have non-default options?
  112. self.has_options = (options is not None) or (serialized_options is not None)
  113. def _SetOptions(self, options, options_class_name):
  114. """Sets the descriptor's options
  115. This function is used in generated proto2 files to update descriptor
  116. options. It must not be used outside proto2.
  117. """
  118. self._options = options
  119. self._options_class_name = options_class_name
  120. # Does this descriptor have non-default options?
  121. self.has_options = options is not None
  122. def GetOptions(self):
  123. """Retrieves descriptor options.
  124. This method returns the options set or creates the default options for the
  125. descriptor.
  126. """
  127. if self._options:
  128. return self._options
  129. from google.protobuf import descriptor_pb2
  130. try:
  131. options_class = getattr(descriptor_pb2,
  132. self._options_class_name)
  133. except AttributeError:
  134. raise RuntimeError('Unknown options class name %s!' %
  135. (self._options_class_name))
  136. with _lock:
  137. if self._serialized_options is None:
  138. self._options = options_class()
  139. else:
  140. self._options = _ParseOptions(options_class(),
  141. self._serialized_options)
  142. return self._options
  143. class _NestedDescriptorBase(DescriptorBase):
  144. """Common class for descriptors that can be nested."""
  145. def __init__(self, options, options_class_name, name, full_name,
  146. file, containing_type, serialized_start=None,
  147. serialized_end=None, serialized_options=None):
  148. """Constructor.
  149. Args:
  150. options: Protocol message options or None
  151. to use default message options.
  152. options_class_name (str): The class name of the above options.
  153. name (str): Name of this protocol message type.
  154. full_name (str): Fully-qualified name of this protocol message type,
  155. which will include protocol "package" name and the name of any
  156. enclosing types.
  157. file (FileDescriptor): Reference to file info.
  158. containing_type: if provided, this is a nested descriptor, with this
  159. descriptor as parent, otherwise None.
  160. serialized_start: The start index (inclusive) in block in the
  161. file.serialized_pb that describes this descriptor.
  162. serialized_end: The end index (exclusive) in block in the
  163. file.serialized_pb that describes this descriptor.
  164. serialized_options: Protocol message serialized options or None.
  165. """
  166. super(_NestedDescriptorBase, self).__init__(
  167. options, serialized_options, options_class_name)
  168. self.name = name
  169. # TODO(falk): Add function to calculate full_name instead of having it in
  170. # memory?
  171. self.full_name = full_name
  172. self.file = file
  173. self.containing_type = containing_type
  174. self._serialized_start = serialized_start
  175. self._serialized_end = serialized_end
  176. def CopyToProto(self, proto):
  177. """Copies this to the matching proto in descriptor_pb2.
  178. Args:
  179. proto: An empty proto instance from descriptor_pb2.
  180. Raises:
  181. Error: If self couldn't be serialized, due to to few constructor
  182. arguments.
  183. """
  184. if (self.file is not None and
  185. self._serialized_start is not None and
  186. self._serialized_end is not None):
  187. proto.ParseFromString(self.file.serialized_pb[
  188. self._serialized_start:self._serialized_end])
  189. else:
  190. raise Error('Descriptor does not contain serialization.')
  191. class Descriptor(_NestedDescriptorBase):
  192. """Descriptor for a protocol message type.
  193. Attributes:
  194. name (str): Name of this protocol message type.
  195. full_name (str): Fully-qualified name of this protocol message type,
  196. which will include protocol "package" name and the name of any
  197. enclosing types.
  198. containing_type (Descriptor): Reference to the descriptor of the type
  199. containing us, or None if this is top-level.
  200. fields (list[FieldDescriptor]): Field descriptors for all fields in
  201. this type.
  202. fields_by_number (dict(int, FieldDescriptor)): Same
  203. :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed
  204. by "number" attribute in each FieldDescriptor.
  205. fields_by_name (dict(str, FieldDescriptor)): Same
  206. :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by
  207. "name" attribute in each :class:`FieldDescriptor`.
  208. nested_types (list[Descriptor]): Descriptor references
  209. for all protocol message types nested within this one.
  210. nested_types_by_name (dict(str, Descriptor)): Same Descriptor
  211. objects as in :attr:`nested_types`, but indexed by "name" attribute
  212. in each Descriptor.
  213. enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references
  214. for all enums contained within this type.
  215. enum_types_by_name (dict(str, EnumDescriptor)): Same
  216. :class:`EnumDescriptor` objects as in :attr:`enum_types`, but
  217. indexed by "name" attribute in each EnumDescriptor.
  218. enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping
  219. from enum value name to :class:`EnumValueDescriptor` for that value.
  220. extensions (list[FieldDescriptor]): All extensions defined directly
  221. within this message type (NOT within a nested type).
  222. extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor
  223. objects as :attr:`extensions`, but indexed by "name" attribute of each
  224. FieldDescriptor.
  225. is_extendable (bool): Does this type define any extension ranges?
  226. oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields
  227. in this message.
  228. oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in
  229. :attr:`oneofs`, but indexed by "name" attribute.
  230. file (FileDescriptor): Reference to file descriptor.
  231. """
  232. if _USE_C_DESCRIPTORS:
  233. _C_DESCRIPTOR_CLASS = _message.Descriptor
  234. def __new__(
  235. cls,
  236. name=None,
  237. full_name=None,
  238. filename=None,
  239. containing_type=None,
  240. fields=None,
  241. nested_types=None,
  242. enum_types=None,
  243. extensions=None,
  244. options=None,
  245. serialized_options=None,
  246. is_extendable=True,
  247. extension_ranges=None,
  248. oneofs=None,
  249. file=None, # pylint: disable=redefined-builtin
  250. serialized_start=None,
  251. serialized_end=None,
  252. syntax=None,
  253. create_key=None):
  254. _message.Message._CheckCalledFromGeneratedFile()
  255. return _message.default_pool.FindMessageTypeByName(full_name)
  256. # NOTE(tmarek): The file argument redefining a builtin is nothing we can
  257. # fix right now since we don't know how many clients already rely on the
  258. # name of the argument.
  259. def __init__(self, name, full_name, filename, containing_type, fields,
  260. nested_types, enum_types, extensions, options=None,
  261. serialized_options=None,
  262. is_extendable=True, extension_ranges=None, oneofs=None,
  263. file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin
  264. syntax=None, create_key=None):
  265. """Arguments to __init__() are as described in the description
  266. of Descriptor fields above.
  267. Note that filename is an obsolete argument, that is not used anymore.
  268. Please use file.name to access this as an attribute.
  269. """
  270. if create_key is not _internal_create_key:
  271. _Deprecated('Descriptor')
  272. super(Descriptor, self).__init__(
  273. options, 'MessageOptions', name, full_name, file,
  274. containing_type, serialized_start=serialized_start,
  275. serialized_end=serialized_end, serialized_options=serialized_options)
  276. # We have fields in addition to fields_by_name and fields_by_number,
  277. # so that:
  278. # 1. Clients can index fields by "order in which they're listed."
  279. # 2. Clients can easily iterate over all fields with the terse
  280. # syntax: for f in descriptor.fields: ...
  281. self.fields = fields
  282. for field in self.fields:
  283. field.containing_type = self
  284. self.fields_by_number = dict((f.number, f) for f in fields)
  285. self.fields_by_name = dict((f.name, f) for f in fields)
  286. self._fields_by_camelcase_name = None
  287. self.nested_types = nested_types
  288. for nested_type in nested_types:
  289. nested_type.containing_type = self
  290. self.nested_types_by_name = dict((t.name, t) for t in nested_types)
  291. self.enum_types = enum_types
  292. for enum_type in self.enum_types:
  293. enum_type.containing_type = self
  294. self.enum_types_by_name = dict((t.name, t) for t in enum_types)
  295. self.enum_values_by_name = dict(
  296. (v.name, v) for t in enum_types for v in t.values)
  297. self.extensions = extensions
  298. for extension in self.extensions:
  299. extension.extension_scope = self
  300. self.extensions_by_name = dict((f.name, f) for f in extensions)
  301. self.is_extendable = is_extendable
  302. self.extension_ranges = extension_ranges
  303. self.oneofs = oneofs if oneofs is not None else []
  304. self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)
  305. for oneof in self.oneofs:
  306. oneof.containing_type = self
  307. self.syntax = syntax or "proto2"
  308. @property
  309. def fields_by_camelcase_name(self):
  310. """Same FieldDescriptor objects as in :attr:`fields`, but indexed by
  311. :attr:`FieldDescriptor.camelcase_name`.
  312. """
  313. if self._fields_by_camelcase_name is None:
  314. self._fields_by_camelcase_name = dict(
  315. (f.camelcase_name, f) for f in self.fields)
  316. return self._fields_by_camelcase_name
  317. def EnumValueName(self, enum, value):
  318. """Returns the string name of an enum value.
  319. This is just a small helper method to simplify a common operation.
  320. Args:
  321. enum: string name of the Enum.
  322. value: int, value of the enum.
  323. Returns:
  324. string name of the enum value.
  325. Raises:
  326. KeyError if either the Enum doesn't exist or the value is not a valid
  327. value for the enum.
  328. """
  329. return self.enum_types_by_name[enum].values_by_number[value].name
  330. def CopyToProto(self, proto):
  331. """Copies this to a descriptor_pb2.DescriptorProto.
  332. Args:
  333. proto: An empty descriptor_pb2.DescriptorProto.
  334. """
  335. # This function is overridden to give a better doc comment.
  336. super(Descriptor, self).CopyToProto(proto)
  337. # TODO(robinson): We should have aggressive checking here,
  338. # for example:
  339. # * If you specify a repeated field, you should not be allowed
  340. # to specify a default value.
  341. # * [Other examples here as needed].
  342. #
  343. # TODO(robinson): for this and other *Descriptor classes, we
  344. # might also want to lock things down aggressively (e.g.,
  345. # prevent clients from setting the attributes). Having
  346. # stronger invariants here in general will reduce the number
  347. # of runtime checks we must do in reflection.py...
  348. class FieldDescriptor(DescriptorBase):
  349. """Descriptor for a single field in a .proto file.
  350. Attributes:
  351. name (str): Name of this field, exactly as it appears in .proto.
  352. full_name (str): Name of this field, including containing scope. This is
  353. particularly relevant for extensions.
  354. index (int): Dense, 0-indexed index giving the order that this
  355. field textually appears within its message in the .proto file.
  356. number (int): Tag number declared for this field in the .proto file.
  357. type (int): (One of the TYPE_* constants below) Declared type.
  358. cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to
  359. represent this field.
  360. label (int): (One of the LABEL_* constants below) Tells whether this
  361. field is optional, required, or repeated.
  362. has_default_value (bool): True if this field has a default value defined,
  363. otherwise false.
  364. default_value (Varies): Default value of this field. Only
  365. meaningful for non-repeated scalar fields. Repeated fields
  366. should always set this to [], and non-repeated composite
  367. fields should always set this to None.
  368. containing_type (Descriptor): Descriptor of the protocol message
  369. type that contains this field. Set by the Descriptor constructor
  370. if we're passed into one.
  371. Somewhat confusingly, for extension fields, this is the
  372. descriptor of the EXTENDED message, not the descriptor
  373. of the message containing this field. (See is_extension and
  374. extension_scope below).
  375. message_type (Descriptor): If a composite field, a descriptor
  376. of the message type contained in this field. Otherwise, this is None.
  377. enum_type (EnumDescriptor): If this field contains an enum, a
  378. descriptor of that enum. Otherwise, this is None.
  379. is_extension: True iff this describes an extension field.
  380. extension_scope (Descriptor): Only meaningful if is_extension is True.
  381. Gives the message that immediately contains this extension field.
  382. Will be None iff we're a top-level (file-level) extension field.
  383. options (descriptor_pb2.FieldOptions): Protocol message field options or
  384. None to use default field options.
  385. containing_oneof (OneofDescriptor): If the field is a member of a oneof
  386. union, contains its descriptor. Otherwise, None.
  387. file (FileDescriptor): Reference to file descriptor.
  388. """
  389. # Must be consistent with C++ FieldDescriptor::Type enum in
  390. # descriptor.h.
  391. #
  392. # TODO(robinson): Find a way to eliminate this repetition.
  393. TYPE_DOUBLE = 1
  394. TYPE_FLOAT = 2
  395. TYPE_INT64 = 3
  396. TYPE_UINT64 = 4
  397. TYPE_INT32 = 5
  398. TYPE_FIXED64 = 6
  399. TYPE_FIXED32 = 7
  400. TYPE_BOOL = 8
  401. TYPE_STRING = 9
  402. TYPE_GROUP = 10
  403. TYPE_MESSAGE = 11
  404. TYPE_BYTES = 12
  405. TYPE_UINT32 = 13
  406. TYPE_ENUM = 14
  407. TYPE_SFIXED32 = 15
  408. TYPE_SFIXED64 = 16
  409. TYPE_SINT32 = 17
  410. TYPE_SINT64 = 18
  411. MAX_TYPE = 18
  412. # Must be consistent with C++ FieldDescriptor::CppType enum in
  413. # descriptor.h.
  414. #
  415. # TODO(robinson): Find a way to eliminate this repetition.
  416. CPPTYPE_INT32 = 1
  417. CPPTYPE_INT64 = 2
  418. CPPTYPE_UINT32 = 3
  419. CPPTYPE_UINT64 = 4
  420. CPPTYPE_DOUBLE = 5
  421. CPPTYPE_FLOAT = 6
  422. CPPTYPE_BOOL = 7
  423. CPPTYPE_ENUM = 8
  424. CPPTYPE_STRING = 9
  425. CPPTYPE_MESSAGE = 10
  426. MAX_CPPTYPE = 10
  427. _PYTHON_TO_CPP_PROTO_TYPE_MAP = {
  428. TYPE_DOUBLE: CPPTYPE_DOUBLE,
  429. TYPE_FLOAT: CPPTYPE_FLOAT,
  430. TYPE_ENUM: CPPTYPE_ENUM,
  431. TYPE_INT64: CPPTYPE_INT64,
  432. TYPE_SINT64: CPPTYPE_INT64,
  433. TYPE_SFIXED64: CPPTYPE_INT64,
  434. TYPE_UINT64: CPPTYPE_UINT64,
  435. TYPE_FIXED64: CPPTYPE_UINT64,
  436. TYPE_INT32: CPPTYPE_INT32,
  437. TYPE_SFIXED32: CPPTYPE_INT32,
  438. TYPE_SINT32: CPPTYPE_INT32,
  439. TYPE_UINT32: CPPTYPE_UINT32,
  440. TYPE_FIXED32: CPPTYPE_UINT32,
  441. TYPE_BYTES: CPPTYPE_STRING,
  442. TYPE_STRING: CPPTYPE_STRING,
  443. TYPE_BOOL: CPPTYPE_BOOL,
  444. TYPE_MESSAGE: CPPTYPE_MESSAGE,
  445. TYPE_GROUP: CPPTYPE_MESSAGE
  446. }
  447. # Must be consistent with C++ FieldDescriptor::Label enum in
  448. # descriptor.h.
  449. #
  450. # TODO(robinson): Find a way to eliminate this repetition.
  451. LABEL_OPTIONAL = 1
  452. LABEL_REQUIRED = 2
  453. LABEL_REPEATED = 3
  454. MAX_LABEL = 3
  455. # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber,
  456. # and kLastReservedNumber in descriptor.h
  457. MAX_FIELD_NUMBER = (1 << 29) - 1
  458. FIRST_RESERVED_FIELD_NUMBER = 19000
  459. LAST_RESERVED_FIELD_NUMBER = 19999
  460. if _USE_C_DESCRIPTORS:
  461. _C_DESCRIPTOR_CLASS = _message.FieldDescriptor
  462. def __new__(cls, name, full_name, index, number, type, cpp_type, label,
  463. default_value, message_type, enum_type, containing_type,
  464. is_extension, extension_scope, options=None,
  465. serialized_options=None,
  466. has_default_value=True, containing_oneof=None, json_name=None,
  467. file=None, create_key=None): # pylint: disable=redefined-builtin
  468. _message.Message._CheckCalledFromGeneratedFile()
  469. if is_extension:
  470. return _message.default_pool.FindExtensionByName(full_name)
  471. else:
  472. return _message.default_pool.FindFieldByName(full_name)
  473. def __init__(self, name, full_name, index, number, type, cpp_type, label,
  474. default_value, message_type, enum_type, containing_type,
  475. is_extension, extension_scope, options=None,
  476. serialized_options=None,
  477. has_default_value=True, containing_oneof=None, json_name=None,
  478. file=None, create_key=None): # pylint: disable=redefined-builtin
  479. """The arguments are as described in the description of FieldDescriptor
  480. attributes above.
  481. Note that containing_type may be None, and may be set later if necessary
  482. (to deal with circular references between message types, for example).
  483. Likewise for extension_scope.
  484. """
  485. if create_key is not _internal_create_key:
  486. _Deprecated('FieldDescriptor')
  487. super(FieldDescriptor, self).__init__(
  488. options, serialized_options, 'FieldOptions')
  489. self.name = name
  490. self.full_name = full_name
  491. self.file = file
  492. self._camelcase_name = None
  493. if json_name is None:
  494. self.json_name = _ToJsonName(name)
  495. else:
  496. self.json_name = json_name
  497. self.index = index
  498. self.number = number
  499. self.type = type
  500. self.cpp_type = cpp_type
  501. self.label = label
  502. self.has_default_value = has_default_value
  503. self.default_value = default_value
  504. self.containing_type = containing_type
  505. self.message_type = message_type
  506. self.enum_type = enum_type
  507. self.is_extension = is_extension
  508. self.extension_scope = extension_scope
  509. self.containing_oneof = containing_oneof
  510. if api_implementation.Type() == 'cpp':
  511. if is_extension:
  512. self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
  513. else:
  514. self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
  515. else:
  516. self._cdescriptor = None
  517. @property
  518. def camelcase_name(self):
  519. """Camelcase name of this field.
  520. Returns:
  521. str: the name in CamelCase.
  522. """
  523. if self._camelcase_name is None:
  524. self._camelcase_name = _ToCamelCase(self.name)
  525. return self._camelcase_name
  526. @staticmethod
  527. def ProtoTypeToCppProtoType(proto_type):
  528. """Converts from a Python proto type to a C++ Proto Type.
  529. The Python ProtocolBuffer classes specify both the 'Python' datatype and the
  530. 'C++' datatype - and they're not the same. This helper method should
  531. translate from one to another.
  532. Args:
  533. proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
  534. Returns:
  535. int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
  536. Raises:
  537. TypeTransformationError: when the Python proto type isn't known.
  538. """
  539. try:
  540. return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
  541. except KeyError:
  542. raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
  543. class EnumDescriptor(_NestedDescriptorBase):
  544. """Descriptor for an enum defined in a .proto file.
  545. Attributes:
  546. name (str): Name of the enum type.
  547. full_name (str): Full name of the type, including package name
  548. and any enclosing type(s).
  549. values (list[EnumValueDescriptors]): List of the values
  550. in this enum.
  551. values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`,
  552. but indexed by the "name" field of each EnumValueDescriptor.
  553. values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`,
  554. but indexed by the "number" field of each EnumValueDescriptor.
  555. containing_type (Descriptor): Descriptor of the immediate containing
  556. type of this enum, or None if this is an enum defined at the
  557. top level in a .proto file. Set by Descriptor's constructor
  558. if we're passed into one.
  559. file (FileDescriptor): Reference to file descriptor.
  560. options (descriptor_pb2.EnumOptions): Enum options message or
  561. None to use default enum options.
  562. """
  563. if _USE_C_DESCRIPTORS:
  564. _C_DESCRIPTOR_CLASS = _message.EnumDescriptor
  565. def __new__(cls, name, full_name, filename, values,
  566. containing_type=None, options=None,
  567. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  568. serialized_start=None, serialized_end=None, create_key=None):
  569. _message.Message._CheckCalledFromGeneratedFile()
  570. return _message.default_pool.FindEnumTypeByName(full_name)
  571. def __init__(self, name, full_name, filename, values,
  572. containing_type=None, options=None,
  573. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  574. serialized_start=None, serialized_end=None, create_key=None):
  575. """Arguments are as described in the attribute description above.
  576. Note that filename is an obsolete argument, that is not used anymore.
  577. Please use file.name to access this as an attribute.
  578. """
  579. if create_key is not _internal_create_key:
  580. _Deprecated('EnumDescriptor')
  581. super(EnumDescriptor, self).__init__(
  582. options, 'EnumOptions', name, full_name, file,
  583. containing_type, serialized_start=serialized_start,
  584. serialized_end=serialized_end, serialized_options=serialized_options)
  585. self.values = values
  586. for value in self.values:
  587. value.type = self
  588. self.values_by_name = dict((v.name, v) for v in values)
  589. # Values are reversed to ensure that the first alias is retained.
  590. self.values_by_number = dict((v.number, v) for v in reversed(values))
  591. def CopyToProto(self, proto):
  592. """Copies this to a descriptor_pb2.EnumDescriptorProto.
  593. Args:
  594. proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto.
  595. """
  596. # This function is overridden to give a better doc comment.
  597. super(EnumDescriptor, self).CopyToProto(proto)
  598. class EnumValueDescriptor(DescriptorBase):
  599. """Descriptor for a single value within an enum.
  600. Attributes:
  601. name (str): Name of this value.
  602. index (int): Dense, 0-indexed index giving the order that this
  603. value appears textually within its enum in the .proto file.
  604. number (int): Actual number assigned to this enum value.
  605. type (EnumDescriptor): :class:`EnumDescriptor` to which this value
  606. belongs. Set by :class:`EnumDescriptor`'s constructor if we're
  607. passed into one.
  608. options (descriptor_pb2.EnumValueOptions): Enum value options message or
  609. None to use default enum value options options.
  610. """
  611. if _USE_C_DESCRIPTORS:
  612. _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor
  613. def __new__(cls, name, index, number,
  614. type=None, # pylint: disable=redefined-builtin
  615. options=None, serialized_options=None, create_key=None):
  616. _message.Message._CheckCalledFromGeneratedFile()
  617. # There is no way we can build a complete EnumValueDescriptor with the
  618. # given parameters (the name of the Enum is not known, for example).
  619. # Fortunately generated files just pass it to the EnumDescriptor()
  620. # constructor, which will ignore it, so returning None is good enough.
  621. return None
  622. def __init__(self, name, index, number,
  623. type=None, # pylint: disable=redefined-builtin
  624. options=None, serialized_options=None, create_key=None):
  625. """Arguments are as described in the attribute description above."""
  626. if create_key is not _internal_create_key:
  627. _Deprecated('EnumValueDescriptor')
  628. super(EnumValueDescriptor, self).__init__(
  629. options, serialized_options, 'EnumValueOptions')
  630. self.name = name
  631. self.index = index
  632. self.number = number
  633. self.type = type
  634. class OneofDescriptor(DescriptorBase):
  635. """Descriptor for a oneof field.
  636. Attributes:
  637. name (str): Name of the oneof field.
  638. full_name (str): Full name of the oneof field, including package name.
  639. index (int): 0-based index giving the order of the oneof field inside
  640. its containing type.
  641. containing_type (Descriptor): :class:`Descriptor` of the protocol message
  642. type that contains this field. Set by the :class:`Descriptor` constructor
  643. if we're passed into one.
  644. fields (list[FieldDescriptor]): The list of field descriptors this
  645. oneof can contain.
  646. """
  647. if _USE_C_DESCRIPTORS:
  648. _C_DESCRIPTOR_CLASS = _message.OneofDescriptor
  649. def __new__(
  650. cls, name, full_name, index, containing_type, fields, options=None,
  651. serialized_options=None, create_key=None):
  652. _message.Message._CheckCalledFromGeneratedFile()
  653. return _message.default_pool.FindOneofByName(full_name)
  654. def __init__(
  655. self, name, full_name, index, containing_type, fields, options=None,
  656. serialized_options=None, create_key=None):
  657. """Arguments are as described in the attribute description above."""
  658. if create_key is not _internal_create_key:
  659. _Deprecated('OneofDescriptor')
  660. super(OneofDescriptor, self).__init__(
  661. options, serialized_options, 'OneofOptions')
  662. self.name = name
  663. self.full_name = full_name
  664. self.index = index
  665. self.containing_type = containing_type
  666. self.fields = fields
  667. class ServiceDescriptor(_NestedDescriptorBase):
  668. """Descriptor for a service.
  669. Attributes:
  670. name (str): Name of the service.
  671. full_name (str): Full name of the service, including package name.
  672. index (int): 0-indexed index giving the order that this services
  673. definition appears within the .proto file.
  674. methods (list[MethodDescriptor]): List of methods provided by this
  675. service.
  676. methods_by_name (dict(str, MethodDescriptor)): Same
  677. :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but
  678. indexed by "name" attribute in each :class:`MethodDescriptor`.
  679. options (descriptor_pb2.ServiceOptions): Service options message or
  680. None to use default service options.
  681. file (FileDescriptor): Reference to file info.
  682. """
  683. if _USE_C_DESCRIPTORS:
  684. _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor
  685. def __new__(
  686. cls,
  687. name=None,
  688. full_name=None,
  689. index=None,
  690. methods=None,
  691. options=None,
  692. serialized_options=None,
  693. file=None, # pylint: disable=redefined-builtin
  694. serialized_start=None,
  695. serialized_end=None,
  696. create_key=None):
  697. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  698. return _message.default_pool.FindServiceByName(full_name)
  699. def __init__(self, name, full_name, index, methods, options=None,
  700. serialized_options=None, file=None, # pylint: disable=redefined-builtin
  701. serialized_start=None, serialized_end=None, create_key=None):
  702. if create_key is not _internal_create_key:
  703. _Deprecated('ServiceDescriptor')
  704. super(ServiceDescriptor, self).__init__(
  705. options, 'ServiceOptions', name, full_name, file,
  706. None, serialized_start=serialized_start,
  707. serialized_end=serialized_end, serialized_options=serialized_options)
  708. self.index = index
  709. self.methods = methods
  710. self.methods_by_name = dict((m.name, m) for m in methods)
  711. # Set the containing service for each method in this service.
  712. for method in self.methods:
  713. method.containing_service = self
  714. def FindMethodByName(self, name):
  715. """Searches for the specified method, and returns its descriptor.
  716. Args:
  717. name (str): Name of the method.
  718. Returns:
  719. MethodDescriptor or None: the descriptor for the requested method, if
  720. found.
  721. """
  722. return self.methods_by_name.get(name, None)
  723. def CopyToProto(self, proto):
  724. """Copies this to a descriptor_pb2.ServiceDescriptorProto.
  725. Args:
  726. proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto.
  727. """
  728. # This function is overridden to give a better doc comment.
  729. super(ServiceDescriptor, self).CopyToProto(proto)
  730. class MethodDescriptor(DescriptorBase):
  731. """Descriptor for a method in a service.
  732. Attributes:
  733. name (str): Name of the method within the service.
  734. full_name (str): Full name of method.
  735. index (int): 0-indexed index of the method inside the service.
  736. containing_service (ServiceDescriptor): The service that contains this
  737. method.
  738. input_type (Descriptor): The descriptor of the message that this method
  739. accepts.
  740. output_type (Descriptor): The descriptor of the message that this method
  741. returns.
  742. options (descriptor_pb2.MethodOptions or None): Method options message, or
  743. None to use default method options.
  744. """
  745. if _USE_C_DESCRIPTORS:
  746. _C_DESCRIPTOR_CLASS = _message.MethodDescriptor
  747. def __new__(cls, name, full_name, index, containing_service,
  748. input_type, output_type, options=None, serialized_options=None,
  749. create_key=None):
  750. _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
  751. return _message.default_pool.FindMethodByName(full_name)
  752. def __init__(self, name, full_name, index, containing_service,
  753. input_type, output_type, options=None, serialized_options=None,
  754. create_key=None):
  755. """The arguments are as described in the description of MethodDescriptor
  756. attributes above.
  757. Note that containing_service may be None, and may be set later if necessary.
  758. """
  759. if create_key is not _internal_create_key:
  760. _Deprecated('MethodDescriptor')
  761. super(MethodDescriptor, self).__init__(
  762. options, serialized_options, 'MethodOptions')
  763. self.name = name
  764. self.full_name = full_name
  765. self.index = index
  766. self.containing_service = containing_service
  767. self.input_type = input_type
  768. self.output_type = output_type
  769. def CopyToProto(self, proto):
  770. """Copies this to a descriptor_pb2.MethodDescriptorProto.
  771. Args:
  772. proto (descriptor_pb2.MethodDescriptorProto): An empty descriptor proto.
  773. Raises:
  774. Error: If self couldn't be serialized, due to too few constructor
  775. arguments.
  776. """
  777. if self.containing_service is not None:
  778. from google.protobuf import descriptor_pb2
  779. service_proto = descriptor_pb2.ServiceDescriptorProto()
  780. self.containing_service.CopyToProto(service_proto)
  781. proto.CopyFrom(service_proto.method[self.index])
  782. else:
  783. raise Error('Descriptor does not contain a service.')
  784. class FileDescriptor(DescriptorBase):
  785. """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto.
  786. Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and
  787. :attr:`dependencies` fields are only set by the
  788. :py:mod:`google.protobuf.message_factory` module, and not by the generated
  789. proto code.
  790. Attributes:
  791. name (str): Name of file, relative to root of source tree.
  792. package (str): Name of the package
  793. syntax (str): string indicating syntax of the file (can be "proto2" or
  794. "proto3")
  795. serialized_pb (bytes): Byte string of serialized
  796. :class:`descriptor_pb2.FileDescriptorProto`.
  797. dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor`
  798. objects this :class:`FileDescriptor` depends on.
  799. public_dependencies (list[FileDescriptor]): A subset of
  800. :attr:`dependencies`, which were declared as "public".
  801. message_types_by_name (dict(str, Descriptor)): Mapping from message names
  802. to their :class:`Desctiptor`.
  803. enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to
  804. their :class:`EnumDescriptor`.
  805. extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension
  806. names declared at file scope to their :class:`FieldDescriptor`.
  807. services_by_name (dict(str, ServiceDescriptor)): Mapping from services'
  808. names to their :class:`ServiceDescriptor`.
  809. pool (DescriptorPool): The pool this descriptor belongs to. When not
  810. passed to the constructor, the global default pool is used.
  811. """
  812. if _USE_C_DESCRIPTORS:
  813. _C_DESCRIPTOR_CLASS = _message.FileDescriptor
  814. def __new__(cls, name, package, options=None,
  815. serialized_options=None, serialized_pb=None,
  816. dependencies=None, public_dependencies=None,
  817. syntax=None, pool=None, create_key=None):
  818. # FileDescriptor() is called from various places, not only from generated
  819. # files, to register dynamic proto files and messages.
  820. # pylint: disable=g-explicit-bool-comparison
  821. if serialized_pb == b'':
  822. # Cpp generated code must be linked in if serialized_pb is ''
  823. try:
  824. return _message.default_pool.FindFileByName(name)
  825. except KeyError:
  826. raise RuntimeError('Please link in cpp generated lib for %s' % (name))
  827. elif serialized_pb:
  828. return _message.default_pool.AddSerializedFile(serialized_pb)
  829. else:
  830. return super(FileDescriptor, cls).__new__(cls)
  831. def __init__(self, name, package, options=None,
  832. serialized_options=None, serialized_pb=None,
  833. dependencies=None, public_dependencies=None,
  834. syntax=None, pool=None, create_key=None):
  835. """Constructor."""
  836. if create_key is not _internal_create_key:
  837. _Deprecated('FileDescriptor')
  838. super(FileDescriptor, self).__init__(
  839. options, serialized_options, 'FileOptions')
  840. if pool is None:
  841. from google.protobuf import descriptor_pool
  842. pool = descriptor_pool.Default()
  843. self.pool = pool
  844. self.message_types_by_name = {}
  845. self.name = name
  846. self.package = package
  847. self.syntax = syntax or "proto2"
  848. self.serialized_pb = serialized_pb
  849. self.enum_types_by_name = {}
  850. self.extensions_by_name = {}
  851. self.services_by_name = {}
  852. self.dependencies = (dependencies or [])
  853. self.public_dependencies = (public_dependencies or [])
  854. def CopyToProto(self, proto):
  855. """Copies this to a descriptor_pb2.FileDescriptorProto.
  856. Args:
  857. proto: An empty descriptor_pb2.FileDescriptorProto.
  858. """
  859. proto.ParseFromString(self.serialized_pb)
  860. def _ParseOptions(message, string):
  861. """Parses serialized options.
  862. This helper function is used to parse serialized options in generated
  863. proto2 files. It must not be used outside proto2.
  864. """
  865. message.ParseFromString(string)
  866. return message
  867. def _ToCamelCase(name):
  868. """Converts name to camel-case and returns it."""
  869. capitalize_next = False
  870. result = []
  871. for c in name:
  872. if c == '_':
  873. if result:
  874. capitalize_next = True
  875. elif capitalize_next:
  876. result.append(c.upper())
  877. capitalize_next = False
  878. else:
  879. result += c
  880. # Lower-case the first letter.
  881. if result and result[0].isupper():
  882. result[0] = result[0].lower()
  883. return ''.join(result)
  884. def _OptionsOrNone(descriptor_proto):
  885. """Returns the value of the field `options`, or None if it is not set."""
  886. if descriptor_proto.HasField('options'):
  887. return descriptor_proto.options
  888. else:
  889. return None
  890. def _ToJsonName(name):
  891. """Converts name to Json name and returns it."""
  892. capitalize_next = False
  893. result = []
  894. for c in name:
  895. if c == '_':
  896. capitalize_next = True
  897. elif capitalize_next:
  898. result.append(c.upper())
  899. capitalize_next = False
  900. else:
  901. result += c
  902. return ''.join(result)
  903. def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
  904. syntax=None):
  905. """Make a protobuf Descriptor given a DescriptorProto protobuf.
  906. Handles nested descriptors. Note that this is limited to the scope of defining
  907. a message inside of another message. Composite fields can currently only be
  908. resolved if the message is defined in the same scope as the field.
  909. Args:
  910. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  911. package: Optional package name for the new message Descriptor (string).
  912. build_file_if_cpp: Update the C++ descriptor pool if api matches.
  913. Set to False on recursion, so no duplicates are created.
  914. syntax: The syntax/semantics that should be used. Set to "proto3" to get
  915. proto3 field presence semantics.
  916. Returns:
  917. A Descriptor for protobuf messages.
  918. """
  919. if api_implementation.Type() == 'cpp' and build_file_if_cpp:
  920. # The C++ implementation requires all descriptors to be backed by the same
  921. # definition in the C++ descriptor pool. To do this, we build a
  922. # FileDescriptorProto with the same definition as this descriptor and build
  923. # it into the pool.
  924. from google.protobuf import descriptor_pb2
  925. file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
  926. file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
  927. # Generate a random name for this proto file to prevent conflicts with any
  928. # imported ones. We need to specify a file name so the descriptor pool
  929. # accepts our FileDescriptorProto, but it is not important what that file
  930. # name is actually set to.
  931. proto_name = binascii.hexlify(os.urandom(16)).decode('ascii')
  932. if package:
  933. file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
  934. proto_name + '.proto')
  935. file_descriptor_proto.package = package
  936. else:
  937. file_descriptor_proto.name = proto_name + '.proto'
  938. _message.default_pool.Add(file_descriptor_proto)
  939. result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
  940. if _USE_C_DESCRIPTORS:
  941. return result.message_types_by_name[desc_proto.name]
  942. full_message_name = [desc_proto.name]
  943. if package: full_message_name.insert(0, package)
  944. # Create Descriptors for enum types
  945. enum_types = {}
  946. for enum_proto in desc_proto.enum_type:
  947. full_name = '.'.join(full_message_name + [enum_proto.name])
  948. enum_desc = EnumDescriptor(
  949. enum_proto.name, full_name, None, [
  950. EnumValueDescriptor(enum_val.name, ii, enum_val.number,
  951. create_key=_internal_create_key)
  952. for ii, enum_val in enumerate(enum_proto.value)],
  953. create_key=_internal_create_key)
  954. enum_types[full_name] = enum_desc
  955. # Create Descriptors for nested types
  956. nested_types = {}
  957. for nested_proto in desc_proto.nested_type:
  958. full_name = '.'.join(full_message_name + [nested_proto.name])
  959. # Nested types are just those defined inside of the message, not all types
  960. # used by fields in the message, so no loops are possible here.
  961. nested_desc = MakeDescriptor(nested_proto,
  962. package='.'.join(full_message_name),
  963. build_file_if_cpp=False,
  964. syntax=syntax)
  965. nested_types[full_name] = nested_desc
  966. fields = []
  967. for field_proto in desc_proto.field:
  968. full_name = '.'.join(full_message_name + [field_proto.name])
  969. enum_desc = None
  970. nested_desc = None
  971. if field_proto.json_name:
  972. json_name = field_proto.json_name
  973. else:
  974. json_name = None
  975. if field_proto.HasField('type_name'):
  976. type_name = field_proto.type_name
  977. full_type_name = '.'.join(full_message_name +
  978. [type_name[type_name.rfind('.')+1:]])
  979. if full_type_name in nested_types:
  980. nested_desc = nested_types[full_type_name]
  981. elif full_type_name in enum_types:
  982. enum_desc = enum_types[full_type_name]
  983. # Else type_name references a non-local type, which isn't implemented
  984. field = FieldDescriptor(
  985. field_proto.name, full_name, field_proto.number - 1,
  986. field_proto.number, field_proto.type,
  987. FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
  988. field_proto.label, None, nested_desc, enum_desc, None, False, None,
  989. options=_OptionsOrNone(field_proto), has_default_value=False,
  990. json_name=json_name, create_key=_internal_create_key)
  991. fields.append(field)
  992. desc_name = '.'.join(full_message_name)
  993. return Descriptor(desc_proto.name, desc_name, None, None, fields,
  994. list(nested_types.values()), list(enum_types.values()), [],
  995. options=_OptionsOrNone(desc_proto),
  996. create_key=_internal_create_key)