Anders and Briegel in Python
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

70 行
1.9KB

  1. import urlparse
  2. from BaseHTTPServer import BaseHTTPRequestHandler
  3. from SimpleHTTPServer import SimpleHTTPRequestHandler
  4. import SocketServer
  5. import sys
  6. import json
  7. import threading
  8. import time
  9. class VizHandler(SimpleHTTPRequestHandler):
  10. """ Handles requests to the server """
  11. def __init__(self, *args, **kwargs):
  12. SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
  13. def get_state(self):
  14. """ Get the current graph state """
  15. self.send_response(200)
  16. self.send_header('Content-Type', 'application/json')
  17. self.end_headers()
  18. state = self.server.state
  19. self.wfile.write(json.dumps({"state":"{}".format(state)}))
  20. def do_GET(self, *args, **kwargs):
  21. """ Someone belled the server """
  22. parsed_path = urlparse.urlparse(self.path)
  23. if parsed_path.path == "/state":
  24. return self.get_state()
  25. else:
  26. return SimpleHTTPRequestHandler.do_GET(self, *args, **kwargs)
  27. class Server(SocketServer.TCPServer):
  28. """ Serves the good stuff """
  29. allow_reuse_address = True
  30. def __init__(self, port = 8000):
  31. self.port = port
  32. self.state = None
  33. SocketServer.TCPServer.__init__(self, ("127.0.0.1", self.port), VizHandler)
  34. def update(self, state):
  35. """ Update the in-memory state """
  36. self.state = state
  37. def run(self):
  38. """ Run in such a way that keyboard interrupts are caught properly """
  39. try:
  40. self.serve_forever()
  41. except KeyboardInterrupt:
  42. self.shutdown()
  43. def start(self):
  44. """ Start in a new thread """
  45. thread = threading.Thread(None, self.run)
  46. thread.daemon = True
  47. thread.start()
  48. print "Go to 127.0.0.0:{}".format(self.port)
  49. if __name__ == '__main__':
  50. server = Server()
  51. server.start()
  52. i=0
  53. while True:
  54. server.update(i)
  55. i += 1
  56. time.sleep(1)
  57. server.shutdown()