Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created June 26, 2012 13:00
Show Gist options
  • Save akhenakh/2995678 to your computer and use it in GitHub Desktop.
Save akhenakh/2995678 to your computer and use it in GitHub Desktop.
An async slow testing server
# pip install tornado then just launch it with python slow_server.py --port=8080
# then call http://localhost:8080/wait/600 for a 600ms request
# Fabrice Aneche https://gist.github.com/2995678
import tornado.web
import tornado.httpserver
import time
import logging
from tornado.options import define, options
define("port", default=8080, help="run on the given port", type=int)
define("address", default=None, help="run on the given Address")
class WaitHandler(tornado.web.RequestHandler):
def prepare(self):
global count
count += 1
self.count = count
@tornado.web.asynchronous
def get(self, timeout):
def _finished():
try:
self.write('#%d OK' % self.count)
self.finish()
logging.debug("#%d FINISHED" % self.count)
except IOError:
pass
logging.debug("#%d START %ss from %s" % (self.count, int(timeout)/1000.0, self.request.remote_ip))
tornado.ioloop.IOLoop.instance().add_timeout(time.time() + int(timeout)/1000.0, _finished)
def post(self, timeout):
self.get(timeout)
def put(self, timeout):
self.get(timeout)
def delete(self, timeout):
self.get(timeout)
def on_connection_close(self):
logging.error('#%d CLOSED before finish' % self.count)
count = 0
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/wait/([0-9]+)", WaitHandler),
]
settings = {
'debug':True,
}
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = Application()
logging.getLogger().setLevel(logging.DEBUG)
http_server = tornado.httpserver.HTTPServer(app, xheaders=True)
http_server.listen(options.port, address=options.address)
main_loop = tornado.ioloop.IOLoop.instance()
main_loop.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment