Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def __json_object_hook(self, d):
- """function to customized the json.loads to return named tuple instead
- of a dict"""
- return namedtuple('response', d.keys())(*d.values())
- def __json2obj(self, data):
- """Helper function which converts the json string into a namedtuple
- so the reponse values can be accessed like objects instead of dicts"""
- return json.loads(data, object_hook=self.__json_object_hook)
- def send(self, command):
- """
- Returns:
- response (dict) - The JSON response from the Server as a dict
- """
- cmd = json.dumps(command)
- cmd = "{:04d}".format(len(cmd)) + cmd
- msg_length = len(cmd)
- # make the first time connection
- if not self.firstDone:
- self.__connect()
- self.firstDone = True
- # Send the message to the server
- totalsent = 0
- while totalsent < msg_length:
- try:
- sent = self.sock.send(cmd[totalsent:])
- totalsent = totalsent + sent
- except socket.error as e:
- self.__connect()
- # Check and recieve the response if available
- parts = []
- resp_length = 0
- recieved = 0
- done = False
- while not done:
- part = self.sock.recv(1024)
- if part == "":
- #Socket connection broken, read empty.
- self.__connect()
- #Reconnected to socket.
- # Find out the length of the response
- if len(part) > 0 and resp_length == 0:
- resp_length = int(part[0:4])
- part = part[4:]
- # Set Done flag
- recieved = recieved + len(part)
- if recieved >= resp_length:
- done = True
- parts.append(part)
- response = "".join(parts)
- # return the JSON as a namedtuple object
- return self.__json2obj(response)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement