m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.4 KiB

6 months ago
  1. from __future__ import absolute_import
  2. import abc
  3. from kafka.protocol.struct import Struct
  4. from kafka.protocol.types import Int16, Int32, String, Schema, Array
  5. class RequestHeader(Struct):
  6. SCHEMA = Schema(
  7. ('api_key', Int16),
  8. ('api_version', Int16),
  9. ('correlation_id', Int32),
  10. ('client_id', String('utf-8'))
  11. )
  12. def __init__(self, request, correlation_id=0, client_id='kafka-python'):
  13. super(RequestHeader, self).__init__(
  14. request.API_KEY, request.API_VERSION, correlation_id, client_id
  15. )
  16. class Request(Struct):
  17. __metaclass__ = abc.ABCMeta
  18. @abc.abstractproperty
  19. def API_KEY(self):
  20. """Integer identifier for api request"""
  21. pass
  22. @abc.abstractproperty
  23. def API_VERSION(self):
  24. """Integer of api request version"""
  25. pass
  26. @abc.abstractproperty
  27. def SCHEMA(self):
  28. """An instance of Schema() representing the request structure"""
  29. pass
  30. @abc.abstractproperty
  31. def RESPONSE_TYPE(self):
  32. """The Response class associated with the api request"""
  33. pass
  34. def expect_response(self):
  35. """Override this method if an api request does not always generate a response"""
  36. return True
  37. def to_object(self):
  38. return _to_object(self.SCHEMA, self)
  39. class Response(Struct):
  40. __metaclass__ = abc.ABCMeta
  41. @abc.abstractproperty
  42. def API_KEY(self):
  43. """Integer identifier for api request/response"""
  44. pass
  45. @abc.abstractproperty
  46. def API_VERSION(self):
  47. """Integer of api request/response version"""
  48. pass
  49. @abc.abstractproperty
  50. def SCHEMA(self):
  51. """An instance of Schema() representing the response structure"""
  52. pass
  53. def to_object(self):
  54. return _to_object(self.SCHEMA, self)
  55. def _to_object(schema, data):
  56. obj = {}
  57. for idx, (name, _type) in enumerate(zip(schema.names, schema.fields)):
  58. if isinstance(data, Struct):
  59. val = data.get_item(name)
  60. else:
  61. val = data[idx]
  62. if isinstance(_type, Schema):
  63. obj[name] = _to_object(_type, val)
  64. elif isinstance(_type, Array):
  65. if isinstance(_type.array_of, (Array, Schema)):
  66. obj[name] = [
  67. _to_object(_type.array_of, x)
  68. for x in val
  69. ]
  70. else:
  71. obj[name] = val
  72. else:
  73. obj[name] = val
  74. return obj