Skip to content

Instantly share code, notes, and snippets.

@minimal
Last active December 11, 2015 10:18
Show Gist options
  • Save minimal/4585818 to your computer and use it in GitHub Desktop.
Save minimal/4585818 to your computer and use it in GitHub Desktop.
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()
@minimal
Copy link
Author

minimal commented Jan 22, 2013

doesn't work with concurrent requests to the same handler

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment