consumers.py 604 B

12345678910111213141516171819202122232425
  1. from channels.generic.websocket import WebsocketConsumer
  2. import json
  3. user_dict = {}
  4. class KnockConsumer(WebsocketConsumer):
  5. # websocket建立连接时执行方法
  6. def connect(self):
  7. self.accept()
  8. username = self.scope.get("url_route").get("kwargs").get("username")
  9. user_dict[username] = self
  10. print(user_dict)
  11. return True
  12. def knock_knock(username, message):
  13. ws = user_dict.get(username)
  14. if ws:
  15. message = json.dumps({'message': message})
  16. ws.send(message)
  17. print(message)
  18. return True
  19. else:
  20. return False