def pop_request(self):
return self.request_queue.get()
- def push_response(self):
+ def push_response(self, item):
self.response_queue.put(item)
def pop_response(self):
def run(self):
while not self.shared.stopped() or self.session.stopped():
response = self.session.pop_response()
+ raw_response = json.dumps(response)
# Possible race condition here by having session
# close connection?
# I assume Python connections are thread safe interfaces
connection = self.session.connection()
try:
- connection.send(response + "\n")
+ connection.send(raw_response + "\n")
except:
self.session.stop()
if raw_buffer == -1:
return True
- command = self.message[0:raw_buffer].strip()
+ raw_command = self.message[0:raw_buffer].strip()
self.message = self.message[raw_buffer + 1:]
- if command == 'quit':
+ if raw_command == 'quit':
return False
try:
- command = json.loads(command)
+ command = json.loads(raw_command)
except:
- print "json error", repr(command)
- continue
+ self.session.push_response(
+ {"error": "bad JSON", "request": raw_command})
+ return True
try:
- message_id = command.get('id')
- method = command.get('method')
- params = command.get('params')
- except:
- print "syntax error", repr(command), self.session.address[0]
- continue
-
- self.session.push_request((message_id, method, params))
- print message_id, method, params
+ # Try to load vital fields, and return an error if
+ # unsuccessful.
+ message_id = command['id']
+ method = command['method']
+ except KeyError:
+ # Return an error JSON in response.
+ self.session.push_response(
+ {"error": "syntax error", "request": raw_command})
+ else:
+ self.session.push_request(command)
+
+ return True
class TcpServer(threading.Thread):