下面是我的问题的最简单示例:
当发出请求时,它将打印 Request via GET <__main__.MainHandler object at 0x104041e10>
然后请求将保持开放状态。好的!但是,当您发出另一个请求时,它不会调用 MainHandler.get
方法直到第一个连接完成。
如何将多个请求发送到 get
方法,同时让它们保持长轮询。我为每个请求传递参数,这些参数将通过 redis 从 pub/sub 获得不同的结果。问题是我一次只能建立一个连接。怎么了?为什么这会阻止其他请求?
import tornado.ioloop
import tornado.web
import os
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
print 'Request via GET', self
if __name__ == '__main__':
application = tornado.web.Application([
(r"/", MainHandler)])
try:
application.listen(int(os.environ.get('PORT', 5000)))
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
左图:如上期所述。请求未按照右图中请求的方式处理。 右图 我需要 RequestHandler 处理请求 (a-d),然后等待 pub/sub 公布其数据。
a b c d + + + + ++ a b c d | | | | || + + + + | | | | || | | | | | | | | || | | | | | | | | || | | | | | v v v || | | | | +---|-----------------------------+ || +-----|----|---|---|------------------+ | | | || | | | | | | | + RequestHandler| || | + + + + RequestHan. | | | | || | | | | | | +---|-----------------------------+ || +-----|----|---|---|------------------+ +---|-----------------------------+ || +-----|----|---|---|------------------+ | | | || | | | | | | | + Sub/Pub Que | || | v + v v Que | | | | || | | | +---|-----------------------------+ || +----------|--------------------------+ +---|-----------------------------+ || +----------|--------------------------+ | || | | Finished || | Finished v || v || || || || || || || ++
如果可以使用其他编程语言来完成此操作,请告诉我。
感谢您的帮助!
最佳答案
来自http://www.tornadoweb.org/en/stable/web.html#tornado.web.asynchronous :
tornado.web.asynchronous(method)
...
If this decorator is given, the response is not finished when the method returns. It is up to the request handler to call self.finish() to finish the HTTP request. Without this decorator, the request is automatically finished when the get() or post() method returns.
您必须显式完成 get
方法:
import tornado.ioloop
import tornado.web
import tornado.options
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
print 'Request via GET', self
self.finish()
if __name__ == '__main__':
application = tornado.web.Application([
(r"/", MainHandler)])
try:
application.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
关于python - Tornado 长轮询请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17135741/