Chris
Chris

Reputation: 40661

Using cyclone or tornado in python, how do i make a simple handler that responds with json?

Do i do it like this?

import cyclone

class MyHandler(cyclone.web.RequestHandler):
    def get(self, command):
        details = {'status':'success'}
        json = json_encode(details)
        self.write(json)

Or is there more to it than that?

Upvotes: 4

Views: 1284

Answers (2)

Schildmeijer
Schildmeijer

Reputation: 20946

I would recommend to use the built in json encoder function :

self.write(tornado.escape.json_encode(details)

If the details is of type dict, tornado will json encode the data automatically. This is not true for lists. From the Tornado code (web.py):

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318798

It's even less than that: You can simply use self.write(details) if it you write a dict, it will be automatically converted to JSON.

Upvotes: 7

Related Questions