Created
November 6, 2012 16:12
-
-
Save johnschimmel/4025736 to your computer and use it in GitHub Desktop.
Sample Flask route to create JSON from Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import jsonify | |
@app.route('/data/ideas') | |
def data_ideas(): | |
# query for the ideas - return oldest first, limit 10 | |
ideas = models.Idea.objects().order_by('+timestamp').limit(10) | |
if ideas: | |
# list to hold ideas | |
public_ideas = [] | |
#prep data for json | |
for i in ideas: | |
tmpIdea = { | |
'creator' : i.creator, | |
'title' : i.title, | |
'idea' : i.idea, | |
'timestamp' : str( i.timestamp ) | |
} | |
# comments / our embedded documents | |
tmpIdea['comments'] = [] # list - will hold all comment dictionaries | |
# loop through idea comments | |
for c in i.comments: | |
comment_dict = { | |
'name' : c.name, | |
'comment' : c.comment, | |
'timestamp' : str( c.timestamp ) | |
} | |
# append comment_dict to ['comments'] | |
tmpIdea['comments'].append(comment_dict) | |
# insert idea dictionary into public_ideas list | |
public_ideas.append( tmpIdea ) | |
# prepare dictionary for JSON return | |
data = { | |
'status' : 'OK', | |
'ideas' : public_ideas | |
} | |
# jsonify (imported from Flask above) | |
# will convert 'data' dictionary and set mime type to 'application/json' | |
return jsonify(data) | |
else: | |
error = { | |
'status' : 'error', | |
'msg' : 'unable to retrieve ideas' | |
} | |
return jsonify(error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment