Last active
November 13, 2016 15:24
-
-
Save drgarcia1986/0bbf877d9c8340d3e9a2 to your computer and use it in GitHub Desktop.
Calling a blocking task asynchronously in Tornado with ThreadPoolExecutor
This file contains 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
# -*- 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() |
This file contains 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
# -*- 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