9

知道如何使用 Tornado 在 python 中输出 JSON 对象。任何好的示例、教程、库或输出 JSONP 对象的一行代码。

4

2 回答 2

23

Tornado 提供了tornado.escape.json_encode,它简单地包装json在 Python 2.6+ 或simplejsonPython 2.5 上。使用简单:

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)
于 2012-07-27T23:49:53.193 回答
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 - 是数据库连接

于 2012-07-27T19:53:59.247 回答