Skip to content

Instantly share code, notes, and snippets.

@johnschimmel
Created November 6, 2012 16:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnschimmel/4025736 to your computer and use it in GitHub Desktop.
Save johnschimmel/4025736 to your computer and use it in GitHub Desktop.
Sample Flask route to create JSON from Dictionary
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