PageRenderTime 29ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/networking/basicWebserver.py

http://stacklessexamples.googlecode.com/
Python | 86 lines | 65 code | 3 blank | 18 comment | 0 complexity | 272037900d7f34f00714b0d2fccbbd4c MD5 | raw file
  1. #
  2. # An example which adapts the standard library module BaseHTTPServer to
  3. # handle concurrent requests each on their own tasklet (as opposed to
  4. # using the ThreadingMixIn from the SocketServer module).
  5. #
  6. # Author: Richard Tew <richard.m.tew@gmail.com>
  7. #
  8. # This code was written to serve as an example of Stackless Python usage.
  9. # Feel free to email me with any questions, comments, or suggestions for
  10. # improvement.
  11. #
  12. # But a better place to discuss Stackless Python related matters is the
  13. # mailing list:
  14. #
  15. # http://www.tismer.com/mailman/listinfo/stackless
  16. #
  17. # Monkeypatch in the stacklesssocket module.
  18. import sys, time
  19. import stackless
  20. import stacklesssocket
  21. #sys.modules["socket"] = stacklesssocket
  22. stacklesssocket.install()
  23. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  24. body = """
  25. <html>
  26. <head>
  27. <title>StacklessHTTPServer page</title>
  28. </head>
  29. <body>
  30. Nothing to see here, move along..
  31. </body>
  32. </html>
  33. """
  34. delays = [ 20, 5 ]
  35. delayIdx = 0
  36. class RequestHandler(BaseHTTPRequestHandler):
  37. # Respect keep alive requests.
  38. protocol_version = "HTTP/1.1"
  39. def do_GET(self):
  40. global delayIdx
  41. self.send_response(200)
  42. self.send_header("Content-type", "text/html")
  43. self.send_header("Content-Length", len(body))
  44. self.end_headers()
  45. t = time.time()
  46. delay = delays[delayIdx % len(delays)]
  47. delayIdx += 1
  48. print stackless.getcurrent(), "blocked", delayIdx, "delay", delay
  49. while time.time() < t + delay:
  50. stackless.schedule()
  51. print stackless.getcurrent(), "done"
  52. self.wfile.write(body)
  53. class StacklessHTTPServer(HTTPServer):
  54. def handle_request(self):
  55. try:
  56. request, client_address = self.get_request()
  57. except socket.error:
  58. return
  59. stackless.tasklet(self.handle_request_tasklet)(request, client_address)
  60. def handle_request_tasklet(self, request, client_address):
  61. if self.verify_request(request, client_address):
  62. try:
  63. self.process_request(request, client_address)
  64. except:
  65. self.handle_error(request, client_address)
  66. self.close_request(request)
  67. def Run():
  68. server = StacklessHTTPServer(('', 80), RequestHandler)
  69. server.serve_forever()
  70. if __name__ == "__main__":
  71. stackless.tasklet(Run)()
  72. stackless.run()