tornado write a Jsonp object

后端 未结 2 485
醉酒成梦
醉酒成梦 2020-12-29 12:53

any idea how to output a JSON object in python using Tornado. Any good examples, tutorial,libraries or one line code which outputs a JSONP object.

相关标签:
2条回答
  • 2020-12-29 13:11

    Tornado provides tornado.escape.json_encode, which simply wraps json on Python 2.6+ or simplejson on Python 2.5. It's simple to use:

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

    outputs:

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

    For a JSONP response:

    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)
    
    0 讨论(0)
  • 2020-12-29 13:12

    You may return json obj in that way

    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
    

    to register class

    def main(db_fn=None):
    
        tornado.options.parse_command_line()
        application = tornado.web.Application([
        (r"/get_datasets", GetDatasetsHandler),
        (r"/get_years", GetYearsHandler),
    )
    

    conn - is database connection

    0 讨论(0)
提交回复
热议问题