Created
October 27, 2016 16:49
-
-
Save pauloalem/c3a44ce6fbbde0128c7c7ccea92f2773 to your computer and use it in GitHub Desktop.
Example of how to offload a blocking task in tornado using the threading module in python3
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
from tornado.httpserver import HTTPServer | |
from tornado.ioloop import IOLoop | |
from tornado.web import Application, RequestHandler | |
from tornado.gen import coroutine, Task | |
import threading | |
from time import sleep | |
def do_block(callback, args): | |
def _callback(): | |
n, = args | |
print("oh") | |
sleep(n) | |
print("hay") | |
IOLoop.instance().add_callback(lambda: callback(n)) | |
t = threading.Thread(target=_callback) | |
t.start() | |
class HandlerA(RequestHandler): | |
@coroutine | |
def get(self): | |
foo = yield Task(do_block, args=(3, )) | |
class HandlerB(RequestHandler): | |
def get(self): | |
self.write("oh hay") | |
self.finish() | |
HTTPServer(Application([ | |
("/a", HandlerA), | |
("/b", HandlerB), | |
], debug=True)).listen(9999) | |
IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment