3

I am using the tornado web framework. Is it possible to make a celery task returning an object of the Future class, in order to use it in an @gen.coroutine decorated handler?

What I am trying to do is the following:

    class TornadoRequestHandler(BaseHandler):

         @gen.coroutine
         def get(self):
              result = yield celery_task.apply_aync()
              self.write(result)
              self.finish()

I've seen tornado-celery, but that isn't exactly what i am trying to achieve.

1 Answer 1

3

As far as I know, the only way to do this is via tornado-celery, which will let you do this:

class TornadoRequestHandler(BaseHandler):

     @gen.coroutine
     def get(self):
          result = yield gen.Task(celery_task.apply_aync)
          self.write(result)
          self.finish()

The reason is that the behavior you want when using gen.coroutine relies on all the async methods it calls to take a callback kwarg, which gets called when the method completes. celery_task.apply_async doesn't take a callback kwarg, so gen.coroutine can't be used directly. It looks like tornado-celery works by exploiting the fact that apply_async does take an **options parameter, which can be any arbitrary kwargs. This means that apply_async actually will accept a callback kwarg, but just ignore it. tornado-celery takes advantage of this by overriding the class in Celery responsible for publishing tasks, and changes the publishing process to publish your task, and then consume from the result queue that gets published to when the tasks completes. The consuming code executes the function provided by the normally ignored callback kwarg, which it pulls out **options.

I'm not sure how clear that explanation, was, but the tl;dr version is tornado-celery provides the simplest way of getting as close possible to the behavior you want.

2
  • HI dano! Thank you for your answer. I think so, too :), and tornado-celery is a nice library, but now i solved it by running the celery tasks in an executor, using a caller function that waits for the task to be finished. It s little code and it wokrs with tornado standard tools.
    – eatdas
    May 26, 2014 at 11:54
  • the concept of result for gen and celery's apply_async are quite different, one is future in ioloop, another one is future in task queue. The later one should be gotten be result.get() while the prior one is by yield. However, the tornado-celery mixed them altogether.
    – Jim Horng
    Oct 8, 2014 at 17:31

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.