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.

72 lines
2.3 KiB

6 months ago
  1. from __future__ import absolute_import
  2. from io import BytesIO
  3. from kafka.protocol.abstract import AbstractType
  4. from kafka.protocol.types import Schema
  5. from kafka.util import WeakMethod
  6. class Struct(AbstractType):
  7. SCHEMA = Schema()
  8. def __init__(self, *args, **kwargs):
  9. if len(args) == len(self.SCHEMA.fields):
  10. for i, name in enumerate(self.SCHEMA.names):
  11. self.__dict__[name] = args[i]
  12. elif len(args) > 0:
  13. raise ValueError('Args must be empty or mirror schema')
  14. else:
  15. for name in self.SCHEMA.names:
  16. self.__dict__[name] = kwargs.pop(name, None)
  17. if kwargs:
  18. raise ValueError('Keyword(s) not in schema %s: %s'
  19. % (list(self.SCHEMA.names),
  20. ', '.join(kwargs.keys())))
  21. # overloading encode() to support both class and instance
  22. # Without WeakMethod() this creates circular ref, which
  23. # causes instances to "leak" to garbage
  24. self.encode = WeakMethod(self._encode_self)
  25. @classmethod
  26. def encode(cls, item): # pylint: disable=E0202
  27. bits = []
  28. for i, field in enumerate(cls.SCHEMA.fields):
  29. bits.append(field.encode(item[i]))
  30. return b''.join(bits)
  31. def _encode_self(self):
  32. return self.SCHEMA.encode(
  33. [self.__dict__[name] for name in self.SCHEMA.names]
  34. )
  35. @classmethod
  36. def decode(cls, data):
  37. if isinstance(data, bytes):
  38. data = BytesIO(data)
  39. return cls(*[field.decode(data) for field in cls.SCHEMA.fields])
  40. def get_item(self, name):
  41. if name not in self.SCHEMA.names:
  42. raise KeyError("%s is not in the schema" % name)
  43. return self.__dict__[name]
  44. def __repr__(self):
  45. key_vals = []
  46. for name, field in zip(self.SCHEMA.names, self.SCHEMA.fields):
  47. key_vals.append('%s=%s' % (name, field.repr(self.__dict__[name])))
  48. return self.__class__.__name__ + '(' + ', '.join(key_vals) + ')'
  49. def __hash__(self):
  50. return hash(self.encode())
  51. def __eq__(self, other):
  52. if self.SCHEMA != other.SCHEMA:
  53. return False
  54. for attr in self.SCHEMA.names:
  55. if self.__dict__[attr] != other.__dict__[attr]:
  56. return False
  57. return True