Skip to content

Instantly share code, notes, and snippets.

@vgoklani
Created July 5, 2013 23:01
Show Gist options
  • Select an option

  • Save vgoklani/5937760 to your computer and use it in GitHub Desktop.

Select an option

Save vgoklani/5937760 to your computer and use it in GitHub Desktop.
# http://papercruncher.com/2013/01/15/truly-async-with-tornado/
import tornado.httpclient
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
import tornado.gen
import tornado.autoreload
import time, json
import tornado.httpserver
class PretendService(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
print 'calling pretend service'
""" Pretend some work is being done by sleeping for 500ms """
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_timeout(time.time() + 0.5, self._finish_req)
def _finish_req(self):
print 'closing friend service'
self.finish()
class MainHandlerBlocking(tornado.web.RequestHandler):
def get(self):
req = tornado.httpclient.HTTPRequest("http://127.0.0.1:8888/external-api", method='GET')
# we could use something like requests or urllib here
client = tornado.httpclient.HTTPClient()
response = client.fetch(req)
# do something with the response
class MainHandlerAsync(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
req = tornado.httpclient.HTTPRequest("http://127.0.0.1:8888/external-api", method='GET')
client = tornado.httpclient.AsyncHTTPClient()
# don't let the yield call confuse you, it's just Tornado helpers to make
# writing async code a bit easier. This is the same as doing
# client.fetch(req, callback=_some_other_helper_function)
response = yield tornado.gen.Task(client.fetch, req)
### do something with the response ###
self.finish()
application = tornado.web.Application([
(r"/async", MainHandlerAsync),
(r"/external-api", PretendService),
(r"/blocking", MainHandlerBlocking)
])
if __name__ == "__main__":
#define("port", default=8888, help="run on the given port", type=int)
#tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.autoreload.start()
tornado.ioloop.IOLoop.instance().start()
'''
lets fire up some benchmarks:
c = 50 concurrent users
n = 1000 requests
> ab -n 1000 -c 50 http://127.0.0.1:8888/blocking
> ab -n 1000 -c 50 http://127.0.0.1:8888/async
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment