Skip to content Skip to sidebar Skip to footer

Python Tornado - How To Implement Long-polling Server To Read From A Queue

I'm trying to build a web server to collect 'commands' via AJAX and then distribute the commands to clients via long-polling. The goal is that someone POSTs some data to /add-comma

Solution 1:

In async model you should omit blocking operation, time.sleep is evil in your code. Moreover, I think that the best way is to use tornado's (in async interface) queue - tornado.queue.Queue and use async get:

import datetime
import tornado.gen
import tornado.queues

_commandQueue = tornado.queues.Queue()


    # ...rest of the code ...    @tornado.gen.coroutinedefgetCommand(self):
        try:
            # wait for queue item if cannot obtain in timeout raise exception
            cmd = yield _commandQueue.get(
                timeout=datetime.timedelta(seconds=_commandPollTimeout)
            )
            return cmd
        except tornado.gen.Timeout:
            returnNone

Note: Module tornado.queues si available since Tornado 4.x, if you use older one, Toro will help.

Solution 2:

You can NOT use sleep in listener, since it blocks reading from input stream. time.sleep(_commandPollInterval). What you should use is yield gen.sleep(_commandPollInterval)

Post a Comment for "Python Tornado - How To Implement Long-polling Server To Read From A Queue"