Skip to content

Instantly share code, notes, and snippets.

@elprup
Last active April 10, 2016 04:44
Show Gist options
  • Save elprup/9389ae6b4f5c7768100316e578b2807a to your computer and use it in GitHub Desktop.
Save elprup/9389ae6b4f5c7768100316e578b2807a to your computer and use it in GitHub Desktop.
Simple example for streamcallback usage in Tornado.
"""
Simple example for streamcallback usage in Tornado.
"""
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
from tornado.options import define, options
define("port", default=8889, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
url = 'http://speedtest.frankfurt.linode.com/100MB-frankfurt.bin'
self.client = tornado.httpclient.AsyncHTTPClient()
request = tornado.httpclient.HTTPRequest(
url=url, streaming_callback=self._on_chunk,
header_callback=self._on_header)
self.client.fetch(request, self._on_download)
def _on_chunk(self, chunk):
self.write('some chunk')
self.flush()
def _on_download(self, response):
self.write('finished')
self.finish()
def _on_header(self, header):
k, v = self._parse_header_string(header)
self.write(header)
self.flush()
self.set_header(k, v)
def _parse_header_string(self, header_string):
comma_index = header_string.find(':')
k = header_string[:comma_index]
v = header_string[comma_index + 1:].strip()
return k, v
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment