sparker-client.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #! /usr/bin/env python
  2. import json
  3. import httplib
  4. sparker_client_default_host = 'localhost'
  5. sparker_client_default_port = 8080
  6. class SparkerClient:
  7. # Configuration
  8. host = sparker_client_default_host
  9. port = sparker_client_default_port
  10. # State
  11. connection = None
  12. session_id = None
  13. output_cursor = 0
  14. # Constants
  15. POST = 'POST'
  16. GET = 'GET'
  17. ROOT = '/'
  18. OK = 200
  19. def __init__(self, host=sparker_client_default_host, port=sparker_client_default_port):
  20. self.host = host
  21. self.port = port
  22. self.connection = self.create_connection()
  23. self.session_id = self.create_session()
  24. def http_json(self, method, url, body=''):
  25. self.connection.request(method, url, body)
  26. response = self.connection.getresponse()
  27. if response.status != self.OK:
  28. raise Exception(str(resonse.status) + ' ' + response.reason)
  29. response_text = response.read()
  30. if len(response_text) != 0:
  31. return json.loads(response_text)
  32. return ''
  33. def create_connection(self):
  34. return httplib.HTTPConnection(self.host, self.port)
  35. def create_session(self):
  36. return self.http_json(self.POST, self.ROOT)
  37. def get_sessions(self):
  38. return self.http_json(self.GET, self.ROOT)
  39. def get_session(self):
  40. return self.http_json(self.GET, self.ROOT + self.session_id)
  41. def post_input(self, command):
  42. self.http_json(self.POST, self.ROOT + self.session_id, command)
  43. def get_output(self):
  44. output = self.get_session()[self.output_cursor:]
  45. self.output_cursor += len(output)
  46. return output
  47. def close_connection(self):
  48. self.connection.close()
  49. import threading
  50. import time
  51. import sys
  52. class SparkerPoller(threading.Thread):
  53. keep_polling = True
  54. def __init__(self, sparker_client):
  55. threading.Thread.__init__(self)
  56. self.sparker_client = sparker_client
  57. def stop_polling(self):
  58. self.keep_polling = False
  59. def run(self):
  60. while self.keep_polling:
  61. output = self.sparker_client.get_output()
  62. for line in output:
  63. print(line)
  64. time.sleep(1)
  65. client = SparkerClient()
  66. poller = SparkerPoller(client)
  67. poller.start()
  68. try:
  69. while True:
  70. line = raw_input()
  71. client.post_input(line)
  72. except:
  73. poller.stop_polling()
  74. # TODO: delete session?
  75. client.close_connection()
  76. sys.exit(0)