Returning response of Tornado POST request

8.5k Views Asked by At

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

2

There are 2 best solutions below

1
Michael Robellard On BEST ANSWER

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)
0
Milovan Tomašević On

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Using it should give you exactly what you want:

self.write(json.dumps({'cbtp': cbtp}))