Search code examples
pythonasynchronouscelerytornado

Python Tornado: how can I make this asynchronous ?


In the below code, when I do message_response.get(), it will make this particular code synchronous. Now is there a way I can make this aynchronous? Just push the code to a broker. And once celery worker is done with the task, I can write the result back to the client?

import tornado.websocket
from celery_main import do_something_celery_task


class HomePageRequestHandler(tornado.websocket.WebSocketHandler):
    def on_message(self, message):
        message_response = do_something_celery_task.apply_async((message,))
        # How can this be a non blocking call? 
        self.write_message(message_response.get())

    def open(self):
        pass

Solution

  • You should try something like this: https://github.com/mher/tornado-celery You'll have code like this, but I don't run it.

    from tornado.websocket import WebSocketHandler
    
    class WebSocketBase(WebSocketHandler):
        @gen.coroutine
        def on_message(self, message):
            response = yield gen.Task(tasks.sleep.apply_async, args=[3])
            self.write_message(str(response.result))