Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I return JSON in flask python fetched from another url to the browser?

Tags:

python

flask

I want to use flask to return JSON to the brower with or without simplejson (with appropriate headers) here is what I have so far for my flask application:

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

Assuming the JSON output returned is:

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

When I visit the page http://localhost:5000 however, I get a Internal Server Error. What must I do with "result" to get it to display appropriately? Or is there some way I can tell it to return with json headers?

When I add a print statement to print the result I can see the JSON, but in the browser it gives me an Internal Server Error.

like image 824
Rolando Avatar asked Aug 08 '12 17:08

Rolando


People also ask

How do I get JSON from post request Flask?

You need to set the request content type to application/json for the . json property and . get_json() method (with no arguments) to work as either will produce None otherwise.


1 Answers

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 is available in flask. Here is the docs

like image 181
Kracekumar Avatar answered Oct 12 '22 00:10

Kracekumar