Search code examples
pythonjsonposttornadoyield-keyword

Returning response of Tornado POST request


I have seen Tornado documentations and examples where self.write method is widely used to render some value on HTML, where the POST request was run in a handler. But I could not find much clarity on how to return the response back to client.

For example, I am calling a POST request on a Tornado server from my client. The code that accepts post request is:

class strest(tornado.web.RequestHandler):
    def post(self):
        value = self.get_argument('key')
        cbtp = cbt.main(value)

With this, I can find the value of cbtp and with self.write(cbtp), I can get it printed in HTML. But instead, I want to return this value to the client in JSON format, like {'cbtp':cbtp} I want to know how to modify my code so that this response is sent to the client, or give me some documentation where this this is fluently explained.

Doing something like

res = {cbtp: cbtp}
return cbtp

throws a BadYieldError: yielded unknown object


Solution

  • You just need to set the output type as JSON and json.dumps your output.

    Normally I have the set_default_headers in a parent class called RESTRequestHandler. If you want just one request that is returning JSON you can set the headers in the post call.

    class strest(tornado.web.RequestHandler):
        def set_default_headers(self):
            self.set_header("Content-Type", 'application/json')
    
        def post(self):
            value = self.get_argument('key')
            cbtp = cbt.main(value)
            r = json.dumps({'cbtp': cbtp})
            self.write(r)