Last active
December 11, 2015 10:18
-
-
Save minimal/4585818 to your computer and use it in GitHub Desktop.
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 functools import partial, wraps | |
from threading import Thread | |
from time import sleep | |
import tornado | |
from tornado.ioloop import IOLoop | |
def threaded(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
if 'callback' in kwargs: | |
orig_cb = kwargs['callback'] | |
else: | |
args, orig_cb = args[:-1], args[-1] | |
io_loop = IOLoop.instance() | |
def callback(*args, **kwargs): | |
io_loop.add_callback(partial(orig_cb, *args, **kwargs)) | |
kwargs['callback'] = callback | |
Thread(target=func, args=args, kwargs=kwargs).start() | |
return wrapper | |
@threaded | |
def slow_func(callback): | |
sleep(1) | |
callback("Hello, world!") | |
class Handler(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
@tornado.gen.engine | |
def get(self): | |
data = yield tornado.gen.Task(slow_func) | |
self.write(data) | |
self.finish() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
doesn't work with concurrent requests to the same handler