example_server.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import socketserver
  2. import threading
  3. from terroroftinytown.six.moves.BaseHTTPServer import (HTTPServer,
  4. BaseHTTPRequestHandler)
  5. class ExampleHandler(BaseHTTPRequestHandler):
  6. def do_GET(self):
  7. shortcode = self.path.split('/', 1)[-1]
  8. if shortcode and hash(shortcode) % 2 == 0:
  9. self.send_response(301)
  10. self.send_header('Location', 'http://www.archiveteam.org/')
  11. self.end_headers()
  12. elif self.path == '/':
  13. self.send_response(200)
  14. self.end_headers()
  15. self.wfile.write(b'Example Server')
  16. else:
  17. self.send_response(404)
  18. self.end_headers()
  19. class ExampleServer(socketserver.ThreadingMixIn, HTTPServer):
  20. def __init__(self, address):
  21. HTTPServer.__init__(self, address, ExampleHandler)
  22. class ExampleServerThread(threading.Thread):
  23. def __init__(self, port=0):
  24. threading.Thread.__init__(self)
  25. self.daemon = True
  26. self._port = port
  27. self._server = ExampleServer(('0.0.0.0', self._port))
  28. self._port = self._server.server_address[1]
  29. self.started_event = threading.Event()
  30. def run(self):
  31. self.started_event.set()
  32. self._server.serve_forever()
  33. def stop(self):
  34. self._server.shutdown()
  35. @property
  36. def port(self):
  37. return self._port
  38. if __name__ == '__main__':
  39. server = ExampleServerThread(8060)
  40. server.start()
  41. server.join()