-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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