Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Last active November 13, 2016 15:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drgarcia1986/0bbf877d9c8340d3e9a2 to your computer and use it in GitHub Desktop.
Save drgarcia1986/0bbf877d9c8340d3e9a2 to your computer and use it in GitHub Desktop.
Calling a blocking task asynchronously in Tornado with ThreadPoolExecutor
# -*- coding: utf-8 -*-
import time
import concurrent.futures
import tornado.web
import tornado.gen
import tornado.httpserver
import tornado.ioloop
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.finish({'hello': 'world'})
class Block(tornado.web.RequestHandler):
def initialize(self, executor):
self.executor = executor
def make_sleep(self):
time.sleep(5)
@tornado.gen.coroutine
def get(self):
yield self.executor.submit(self.make_sleep)
self.finish({'msg': 'finish blocking call'})
if __name__ == '__main__':
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
app = tornado.web.Application(
[
(r'/', IndexHandler),
(r'/block/', Block, dict(executor=executor)),
]
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(8000)
tornado.ioloop.IOLoop.instance().start()
# -*- coding: utf-8 -*-
import time
import concurrent.futures
import tornado.concurrent
import tornado.web
import tornado.gen
import tornado.httpserver
import tornado.ioloop
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.finish({'hello': 'world'})
class Block(tornado.web.RequestHandler):
def initialize(self, executor):
self.executor = executor
@tornado.concurrent.run_on_executor
def make_sleep(self):
time.sleep(5)
@tornado.gen.coroutine
def get(self):
yield self.make_sleep()
self.finish({'msg': 'finish blocking call'})
if __name__ == '__main__':
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
app = tornado.web.Application(
[
(r'/', IndexHandler),
(r'/block/', Block, dict(executor=executor)),
]
)
http_server = tornado.httpserver.HTTPServer(app)
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