aboutsummaryrefslogtreecommitdiff
path: root/budget/rest.py
diff options
context:
space:
mode:
authorAlexis Metaireau <alexis@notmyidea.org>2011-09-13 11:27:36 +0200
committerAlexis Metaireau <alexis@notmyidea.org>2011-09-13 11:27:36 +0200
commitd2e2260e522cf4b7de24dbb2adbb3bfb12ee01f3 (patch)
treedc3caed10008f20e98973b2ad539b25cb2ee46d7 /budget/rest.py
parentef3d761fc70c1c2bf0d45dde6d2703c73715bf6c (diff)
downloadihatemoney-mirror-d2e2260e522cf4b7de24dbb2adbb3bfb12ee01f3.zip
ihatemoney-mirror-d2e2260e522cf4b7de24dbb2adbb3bfb12ee01f3.tar.gz
ihatemoney-mirror-d2e2260e522cf4b7de24dbb2adbb3bfb12ee01f3.tar.bz2
Add a serialization mechanism
Diffstat (limited to 'budget/rest.py')
-rw-r--r--budget/rest.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/budget/rest.py b/budget/rest.py
index 5ecee69..3a911ab 100644
--- a/budget/rest.py
+++ b/budget/rest.py
@@ -1,3 +1,5 @@
+import json
+
class RESTResource(object):
"""Represents a REST resource, with the different HTTP verbs"""
_NEED_ID = ["get", "update", "delete"]
@@ -70,6 +72,9 @@ class RESTResource(object):
method = need_auth(self._authentifier,
self._inject_name or self._name)(method)
+ # regarding the format, transform the response
+ method = serialize("json")(method) #FIXME handle headers
+
app.add_url_rule(
self._get_route_for(action),
"%s_%s" % (self._name, action),
@@ -111,3 +116,27 @@ def need_auth(authentifier, name=None, remove_attr=True):
raise werkzeug.exceptions.Forbidden()
return wrapped
return wrapper
+
+
+# serializers
+
+def serialize(format):
+ def wrapper(func):
+ def wrapped(*args, **kwargs):
+ return SERIALIZERS[format].encode(func(*args, **kwargs))
+ return wrapped
+ return wrapper
+
+
+class JSONEncoder(json.JSONEncoder):
+ def default(self, o):
+ if hasattr(o, "_to_serialize"):
+ # build up the object
+ data = {}
+ for attr in o._to_serialize:
+ data[attr] = getattr(o, attr)
+ return data
+ else:
+ return json.JSONEncoder.default(self, o)
+
+SERIALIZERS = {"json": JSONEncoder()}