Anders and Briegel in Python
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

58 linhas
1.6KB

  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. state = 0
  10. class VizHandler(SimpleHTTPRequestHandler):
  11. """ Handles requests to the server """
  12. def __init__(self, *args, **kwargs):
  13. SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
  14. def get_state(self):
  15. self.send_response(200)
  16. self.send_header('Content-Type', 'application/json')
  17. self.end_headers()
  18. self.wfile.write(json.dumps({"state":"{}".format(state)}))
  19. def do_GET(self, *args, **kwargs):
  20. parsed_path = urlparse.urlparse(self.path)
  21. print parsed_path.path
  22. if parsed_path.path == "/state":
  23. return self.get_state()
  24. else:
  25. return SimpleHTTPRequestHandler.do_GET(self, *args, **kwargs)
  26. class VizServer(SocketServer.TCPServer):
  27. """ Runs the server in a new thread """
  28. allow_reuse_address = True
  29. def __init__(self, port = 8000):
  30. self.port = port
  31. SocketServer.TCPServer.__init__(self, ("127.0.0.1", self.port), VizHandler)
  32. def run(self):
  33. try:
  34. self.serve_forever()
  35. except KeyboardInterrupt:
  36. "Caught keyboard interrupt"
  37. self.shutdown()
  38. def start(self):
  39. thread = threading.Thread(None, self.run)
  40. thread.daemon = True
  41. thread.start()
  42. print "Go to 127.0.0.0:{}".format(self.port)
  43. if __name__ == '__main__':
  44. server = VizServer()
  45. server.start()
  46. while True:
  47. state += 1
  48. time.sleep(1)
  49. server.shutdown()