aboutsummaryrefslogtreecommitdiff
path: root/ihatemoney/utils.py
diff options
context:
space:
mode:
author0livd <github@destras.fr>2018-01-25 17:41:28 +0100
committerAlexis Metaireau <alexis@notmyidea.org>2018-01-25 17:41:28 +0100
commitb93ea4830d5290def99d597f17292a8aa5d4c090 (patch)
treebeb34a47d9eb85643672cc3b743c9b6d37932092 /ihatemoney/utils.py
parent830718e1fe5f18959f455a696ebc2172a2d5f253 (diff)
downloadihatemoney-mirror-b93ea4830d5290def99d597f17292a8aa5d4c090.zip
ihatemoney-mirror-b93ea4830d5290def99d597f17292a8aa5d4c090.tar.gz
ihatemoney-mirror-b93ea4830d5290def99d597f17292a8aa5d4c090.tar.bz2
API: Migrate from flask-rest to flask-restful (#315)
The flask-rest custom json encoder is still needed and thus was added to ihatemoney's utils. Closes #298
Diffstat (limited to 'ihatemoney/utils.py')
-rw-r--r--ihatemoney/utils.py27
1 files changed, 26 insertions, 1 deletions
diff --git a/ihatemoney/utils.py b/ihatemoney/utils.py
index 6af0112..aaae2a0 100644
--- a/ihatemoney/utils.py
+++ b/ihatemoney/utils.py
@@ -3,7 +3,7 @@ import re
from io import BytesIO, StringIO
from jinja2 import filters
-from json import dumps
+from json import dumps, JSONEncoder
from flask import redirect
from werkzeug.routing import HTTPException, RoutingException
import six
@@ -170,3 +170,28 @@ class LoginThrottler():
def reset(self, ip):
self._attempts.pop(ip, None)
+
+
+class IhmJSONEncoder(JSONEncoder):
+ """Subclass of the default encoder to support custom objects.
+ Taken from the deprecated flask-rest package."""
+ 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
+ elif hasattr(o, "isoformat"):
+ return o.isoformat()
+ else:
+ try:
+ from flask_babel import speaklater
+ if isinstance(o, speaklater.LazyString):
+ try:
+ return unicode(o) # For python 2.
+ except NameError:
+ return str(o) # For python 3.
+ except ImportError:
+ pass
+ return JSONEncoder.default(self, o)