Search code examples
pythontornadoyield

Python Tornado BadYieldError for POST request with timeout


I'm trying to write a post request for a Python Tornado server that sleeps for a second before sending a response back to a client. The server must handle many of these post requests per minute. The following code doesn't work because of 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("{}")

The server is to receive a post request, wait a second, and then return the result without blocking other requests. This is Python 2.7. How to resolve this? Thanks!


Solution

  • Either use callbacks or "yield", not both. So you could do:

    @asynchronous
    def post(self):
        IOLoop.instance().add_timeout(time.time() + 1, self._process)
    
    def _process(self):
        self.write("{}")
        self.finish()
    

    Or, better:

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