【问题标题】:tornado asynchronous request does't work,what's wrong with my code?龙卷风异步请求不起作用,我的代码有什么问题?
【发布时间】:2014-07-13 10:46:12
【问题描述】:

这是我的代码:

 class AsyncTestHandler(BaseHandler):
  def testTimeOut(self, callback):
      time.sleep(20)
      callback("ok")

  @tornado.web.asynchronous
  def post(self):
      user = self.get_current_user()
      self.testTimeOut(callback=self.respones)

  def respones(self,msg):
      self.finish(msg)

我用了“@tornado.web.asynchronous”的回调,但是请求不是异步的,怎么id?

【问题讨论】:

标签: python asynchronous tornado


【解决方案1】:

Tornado 只使用一个进程和一个线程。其中所有的IO操作都是异步的,并不代表它们是并发处理的。因此,如果您在代码中的任何位置调用 time.sleep(xx),您的 Tornado 进程将在那时完全“停止”!

Tornado 的正确睡眠方式是拨打ioloop.add_timeout

tornado equivalent of delay

http://caisong.com/Tornado%20don't%20use%20time.sleep%20.html

【讨论】:

    【解决方案2】:

    问题是,time.sleep 不是异步的,所以主循环在睡眠时被阻塞。对于异步运行同步代码,您可以使用单独的工作线程。

    class HugeQueryHandler(BaseHandler):
    
        executor = tornado.concurrent.futures.ThreadPoolExecutor(5)
    
        @tornado.concurrent.run_on_executor
        def sleep_async(self):
            time.sleep(20)
            return
    
        @tornado.web.asynchronous
        @gen.engine
        def get(self):
            r = yield self.sleep_async()
            self.finish()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      相关资源
      最近更新 更多