龙卷风写一个Json对象

时间:2012-07-27 19:04:31

标签: python json tornado

任何想法如何使用Tornado在python中输出JSON对象。任何好的例子,教程,库或输出JSONP对象的一行代码。

2 个答案:

答案 0 :(得分:23)

Tornado提供tornado.escape.json_encode,它只是在Python 2.6上包装json或在Python 2.5上包装simplejson。它使用简单:

from tornado.escape import json_encode
obj = { 
    'foo': 'bar',
     '1': 2,
     'false': True 
    }
self.write(json_encode(obj))

输出:

{"1": 2, "foo": "bar", "false": true}

对于JSONP响应:

callback = self.get_argument('callback')
jsonp = "{jsfunc}({json});".format(jsfunc=callback,
    json=json_encode(obj))
self.set_header('Content-Type', 'application/javascript')
self.write(jsonp)

答案 1 :(得分:1)

你可以这样返回json obj

import json

class GetYearsHandler(tornado.web.RequestHandler):
    def get(self):
        try:
            response = get_years(self.get_argument("dataset_id"))
            result = {'status':'success', 'response': response}
            kk = tornado.escape.json_encode(result)
            kk = wrap_callback(self, kk)
            self.write(kk)
        except Exception, e:
            print >> sys.stderr, "Error occured:\n%s" % format_exc()
            self.write(json.dumps({'status': 'fail', 'error': "Error occured:\n%s" % format_exc()}))

def get_years (dataset_id):
    dates=[]
    years=[]
    conn = condb()
    cur = conn.cursor()
    data = {'dataset_id':dataset_id}
    cur.execute("SELECT layers.start_time FROM layers, datasets WHERE (layers.dataset_id=datasets.id) AND (datasets.business_id=%(dataset_id)s)",data)
    for row in cur.fetchall():
        dates.append(row[0])
    date=""
    for date in dates:
        year = int(date.year)
        if not year in years:
            years.append(year)
    conn.close()
    years.sort()
    return years

注册课程

def main(db_fn=None):

    tornado.options.parse_command_line()
    application = tornado.web.Application([
    (r"/get_datasets", GetDatasetsHandler),
    (r"/get_years", GetYearsHandler),
)

conn - 是数据库连接