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.
Post a Comment for "Python Tornado - How To Implement Long-polling Server To Read From A Queue"