Commits

Steven Kryskalla committed dc49d96

return JSON everywhere

Comments (0)

Files changed (1)

 from pymongo import Connection
 from pymongo.objectid import ObjectId
 import bson
+from json import dumps as json_dumps
 
 from flask import Flask, request
 app = Flask(__name__)
 db = conn[app.config['MONGO_COLLECTION_NAME']]
 db.authenticate(app.config['MONGO_AUTH_USER'], app.config['MONGO_AUTH_PASSWORD'])
 
+def objectid_to_json(obj):
+    if isinstance(obj, ObjectId):
+        return str(obj)
+    return obj
+
+dumps = lambda obj: json_dumps(obj, default=objectid_to_json)
+
 @app.route("/")
 def index():
-    return repr(list(db.cards.find()))
+    return dumps(list(db.cards.find()))
 
 @app.route("/cards/add")
 def addcard():
     card = {}
     for p in required:
         if p not in params:
-            return "Missing param: %s" % p
+            return dumps({'error': "Missing param: %s" % p})
         card[p] = params.pop(p)
     for extra in params.keys():
         card[extra] = params.pop(extra)
     obj = db.cards.insert(card)
-    return repr(obj)
+    return dumps({"_id": obj})
 
 @app.route("/cards/delete/<cardid>")
 def deletecard(cardid):
         objid = ObjectId(cardid)
         db.cards.remove({'_id': objid})
     except bson.errors.InvalidId:
-        return 'Object not found - Nothing Deleted'
-    return 'Deleted'
+        return dumps({'deleted': 0, 'error': 'Object not found - Nothing Deleted'})
+    return dumps({'deleted': 1, 'error': ''})
 
 @app.route("/cards/<cardid>")
 def getcard(cardid):
         obj = db.cards.find({'_id': ObjectId(cardid)})
     except bson.errors.InvalidId:
         obj = []
-    return repr(list(obj))
+    return dumps(list(obj))
 
 if __name__ == "__main__":
     app.run(host=app.config['APP_HOST'], port=app.config['APP_PORT'])