Skip to content

Instantly share code, notes, and snippets.

@ego008
Forked from methane/gist:2185380
Last active December 26, 2018 11:51
Show Gist options
  • Save ego008/52aa72ffdbd41ff33af99260b0e26f2e to your computer and use it in GitHub Desktop.
Save ego008/52aa72ffdbd41ff33af99260b0e26f2e to your computer and use it in GitHub Desktop.
Tornado Example: Delegating an blocking task to a worker thread pool from an asynchronous request handler
import time
import tornado
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor # `pip install futures` for python2
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado import gen
MAX_WORKERS = 4
class Handler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
@run_on_executor
def background_task(self, i):
""" This will be executed in `executor` pool. """
time.sleep(10)
return i
@gen.coroutine
def get(self, idx):
""" Request that asynchronously calls background task. """
res = yield self.background_task(idx)
self.write(res)
HTTPServer(Application([("/(\d+)", Handler)],debug=True)).listen(8888)
IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment