Skip to content

Instantly share code, notes, and snippets.

@shyal
Last active February 15, 2017 09:11
Show Gist options
  • Save shyal/96ce8e9e721d6a0bc5a9484240b185c7 to your computer and use it in GitHub Desktop.
Save shyal/96ce8e9e721d6a0bc5a9484240b185c7 to your computer and use it in GitHub Desktop.
This example shows how to use the tornado AsyncHTTPClient concurrently to perform multiple gets
from tornado import gen, web, ioloop, httpclient
import json
class MainHandler(web.RequestHandler):
@gen.coroutine
def get(self):
http_client = httpclient.AsyncHTTPClient()
time, ip, headers = yield [http_client.fetch("http://time.ioloop.io?format=json"),
http_client.fetch("http://ip.ioloop.io?format=json"),
http_client.fetch("http://headers.ioloop.io?format=json")]
self.write({
"time": json.loads(time.body),
"ip": json.loads(ip.body),
"headers": json.loads(headers.body)
})
app = web.Application([("/", MainHandler)], debug=True)
app.listen(8888)
ioloop.IOLoop.current().start()
@shyal
Copy link
Author

shyal commented Feb 14, 2017

import time
import tornado.web
from tornado.ioloop import IOLoop
from tornado import gen


class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @gen.engine
    def get(self):
        self.write("hello ")
        yield gen.Task(IOLoop.instance().add_timeout, time.time() + 1)
        self.write("world")
        self.finish()


application = tornado.web.Application([
    (r"/", MainHandler),
    ])


if __name__ == "__main__":
    application.listen(8888)
    IOLoop.instance().start()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment