Skip to content

Instantly share code, notes, and snippets.

@screeley
Created August 11, 2011 19:17
Show Gist options
  • Save screeley/1140499 to your computer and use it in GitHub Desktop.
Save screeley/1140499 to your computer and use it in GitHub Desktop.
import time
import functools
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.wsgi
import tornado.httpclient
class Urls(object):
def __init__(self, urls):
self.urls = dict([(i, url) for i, url in enumerate(urls)])
self.responses = {}
self.callbacks = []
def _callback(self, id, response):
self.callbacks.remove(id)
self.responses[id] = response
def fetch(self):
http = tornado.httpclient.AsyncHTTPClient()
for id, url in self.urls.items():
self.callbacks.append(id)
http.fetch(url, callback=functools.partial(self._callback, id))
class Waiter(object):
def __init__(self, callback, io_loop=None):
self.io_loop = io_loop or tornado.ioloop.IOLoop.instance()
self.callback = callback
def wait(self, obj):
"""
Waits for the current set of callbacks to complete before moving on.
"""
if obj.callbacks:
self.io_loop.add_timeout(time.time() + 0.3, functools.partial(self.wait, obj))
else:
try:
self.callback(obj)
except Exception, e:
self.finish()
def start(self, obj):
obj.fetch()
self.wait(obj)
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
obj = Urls(['http://google.com', 'http://apple.com', 'http://yahoo.com', 'http://microsoft.com'])
waiter = Waiter(self._print_servers)
waiter.start(obj)
def _print_servers(self, obj):
self.write('<html><body>')
for response in obj.responses.values():
self.write('%s <br/>' % response.headers.get('Server'))
self.write('</body></html>')
self.finish()
url_mapping = [
('/', MainHandler)
]
app_settings = {
"debug": True,
}
if __name__ == "__main__":
application = tornado.web.Application(url_mapping, **app_settings)
http_server = tornado.httpserver.HTTPServer(application, xheaders=True)
http_server.listen(8000)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment