sparker-client.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. DELETE = 'DELETE'
  18. ROOT = '/'
  19. OK = 200
  20. def __init__(self, host=sparker_client_default_host, port=sparker_client_default_port):
  21. self.host = host
  22. self.port = port
  23. self.connection = self.create_connection()
  24. self.session_id = self.create_session()
  25. def http_json(self, method, url, body=''):
  26. self.connection.request(method, url, body)
  27. response = self.connection.getresponse()
  28. if response.status != self.OK:
  29. raise Exception(str(response.status) + ' ' + response.reason)
  30. response_text = response.read()
  31. if len(response_text) != 0:
  32. return json.loads(response_text)
  33. return ''
  34. def create_connection(self):
  35. return httplib.HTTPConnection(self.host, self.port)
  36. def create_session(self):
  37. return self.http_json(self.POST, self.ROOT)
  38. def get_sessions(self):
  39. return self.http_json(self.GET, self.ROOT)
  40. def get_session(self):
  41. return self.http_json(self.GET, self.ROOT + self.session_id)
  42. def post_input(self, command):
  43. self.http_json(self.POST, self.ROOT + self.session_id, command)
  44. def get_output(self):
  45. output = self.get_session()[self.output_cursor:]
  46. self.output_cursor += len(output)
  47. return output
  48. def delete_session(self):
  49. self.http_json(self.DELETE, self.ROOT + self.session_id)
  50. def close_connection(self):
  51. self.connection.close()
  52. import threading
  53. import time
  54. import sys
  55. class SparkerPoller(threading.Thread):
  56. keep_polling = True
  57. def __init__(self, sparker_client):
  58. threading.Thread.__init__(self)
  59. self.sparker_client = sparker_client
  60. def stop_polling(self):
  61. self.keep_polling = False
  62. def run(self):
  63. while self.keep_polling:
  64. output = self.sparker_client.get_output()
  65. for line in output:
  66. print(line)
  67. time.sleep(1)
  68. client = SparkerClient()
  69. poller = SparkerPoller(client)
  70. poller.start()
  71. try:
  72. while True:
  73. line = raw_input()
  74. client.post_input(line)
  75. except:
  76. poller.stop_polling()
  77. client.delete_session()
  78. client.close_connection()
  79. sys.exit(0)