如何将从另一个URL获取的flask python中的JSON返回给浏览器?

时间:2012-08-08 17:59:14

标签: python flask

我想使用flask将JSON返回给浏览器,有或没有simplejson(带有适当的标题)这是我到目前为止我的烧瓶应用程序:

@app.route('/')
def hello_world():
    QUERY_URL="http://someappserver:9902/myjsonservlet"
    result = simplejson.load(urllib.urlopen(QUERY_URL))
    return result;

假设返回的JSON输出为:

{"myapplication":{"system_memory":21026160640.0,"percent_memory":0.34,
"total_queue_memory":4744,"consumers":1,"messages_unacknowledged":0,
"total_messages":0,"connections":1}

当我访问页面http://localhost:5000时,我得到Internal Server Error。我必须对“结果”做些什么才能让它正确显示?或者有什么方法可以告诉它返回json标题?

当我添加一个print语句来打印结果时,我可以看到JSON,但在浏览器中它给了我一个Internal Server Error

1 个答案:

答案 0 :(得分:10)

import requests
r = requests.get(QUERY_URL)
return r.json

#normal return
return jsonify(username=g.user.username,
               email=g.user.email,
               id=g.user.id)

jsonify可用于烧瓶。这是docs