messages.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import json
  2. class Message:
  3. MESSAGE_TYPES = {}
  4. @classmethod
  5. def decode(cls, raw):
  6. hash = json.loads(raw)
  7. tag = hash['tag']
  8. return cls.MESSAGE_TYPES[tag].from_hash(hash)
  9. def json(self):
  10. hash = self.to_hash()
  11. return json.dumps(self.to_hash())
  12. def message(name):
  13. def decorate(class_decl):
  14. Message.MESSAGE_TYPES[name] = class_decl
  15. return class_decl
  16. return decorate
  17. @message('config')
  18. class InitialConfig(Message):
  19. def __init__(self, user, game):
  20. self.user = user
  21. self.game = game
  22. @classmethod
  23. def from_hash(cls, d):
  24. return cls(user=d['user'], game=d['game'])
  25. def to_hash(self):
  26. return {'user': self.user, 'game': self.game}
  27. @message('post')
  28. class Post(Message):
  29. def __init__(self, author, content):
  30. self.author = author
  31. self.content = content
  32. @classmethod
  33. def from_hash(cls, d):
  34. return cls(author=d['author'], content=d['content'])
  35. def to_hash(self):
  36. return {
  37. 'tag': 'post',
  38. 'author': self.author,
  39. 'content': self.content,
  40. }