Advertisement
Guest User

Untitled

a guest
Aug 21st, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. def __json_object_hook(self, d):
  2. """function to customized the json.loads to return named tuple instead
  3. of a dict"""
  4. return namedtuple('response', d.keys())(*d.values())
  5. def __json2obj(self, data):
  6. """Helper function which converts the json string into a namedtuple
  7. so the reponse values can be accessed like objects instead of dicts"""
  8. return json.loads(data, object_hook=self.__json_object_hook)
  9. def send(self, command):
  10. """
  11. Returns:
  12. response (dict) - The JSON response from the Server as a dict
  13. """
  14. cmd = json.dumps(command)
  15. cmd = "{:04d}".format(len(cmd)) + cmd
  16. msg_length = len(cmd)
  17.  
  18. # make the first time connection
  19. if not self.firstDone:
  20. self.__connect()
  21. self.firstDone = True
  22.  
  23. # Send the message to the server
  24. totalsent = 0
  25. while totalsent < msg_length:
  26. try:
  27. sent = self.sock.send(cmd[totalsent:])
  28. totalsent = totalsent + sent
  29. except socket.error as e:
  30. self.__connect()
  31.  
  32. # Check and recieve the response if available
  33. parts = []
  34. resp_length = 0
  35. recieved = 0
  36. done = False
  37. while not done:
  38. part = self.sock.recv(1024)
  39. if part == "":
  40. #Socket connection broken, read empty.
  41. self.__connect()
  42. #Reconnected to socket.
  43.  
  44. # Find out the length of the response
  45. if len(part) > 0 and resp_length == 0:
  46. resp_length = int(part[0:4])
  47. part = part[4:]
  48.  
  49. # Set Done flag
  50. recieved = recieved + len(part)
  51. if recieved >= resp_length:
  52. done = True
  53.  
  54. parts.append(part)
  55.  
  56. response = "".join(parts)
  57. # return the JSON as a namedtuple object
  58. return self.__json2obj(response)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement