Python Tornado BadYieldError POST 请求超时

Python Tornado BadYieldError for POST request with timeout

我正在尝试为 Python Tornado 服务器编写 post 请求,该服务器在将响应发送回客户端之前休眠一秒钟。服务器每分钟必须处理许多这样的 post 请求。由于 BadYieldError: yielded unknown object <generator object get at 0x10d0b8870>

,以下代码不起作用
@asynchronous
def post(self):
    response = yield IOLoop.instance().add_timeout(time.time() + 1, self._process)
    self.write(response)
    self.finish()

@gen.coroutine
def _process(self, callback=None):
    callback("{}")

服务器要接收一个post请求,稍等片刻,然后return结果,不会阻塞其他请求。这是 Python 2.7。如何解决这个问题?谢谢!

使用回调或 "yield",不能同时使用。所以你可以这样做:

@asynchronous
def post(self):
    IOLoop.instance().add_timeout(time.time() + 1, self._process)

def _process(self):
    self.write("{}")
    self.finish()

或者,更好:

@gen.coroutine
def post(self):
    yield gen.sleep(1)
    self.write("{}")
    # Tornado calls self.finish when coroutine exits.