Fix exceptions raised when a lazy text is used in json dump

This commit is contained in:
Shadi Naif
2018-10-07 15:46:03 +03:00
parent c0e2fd676a
commit 4df2073376
21 changed files with 107 additions and 48 deletions

View File

@@ -0,0 +1,29 @@
"""
Helpers for json serialization
"""
import datetime
from django.core.serializers.json import DjangoJSONEncoder
from opaque_keys.edx.keys import CourseKey, UsageKey
class EdxJSONEncoder(DjangoJSONEncoder):
"""
Custom JSONEncoder that handles `Location` and `datetime.datetime` objects.
`Location`s are encoded as their url string form, and `datetime`s as
ISO date strings
"""
def default(self, o): # pylint: disable=method-hidden
if isinstance(o, (CourseKey, UsageKey)):
return unicode(o)
elif isinstance(o, datetime.datetime):
if o.tzinfo is not None:
if o.utcoffset() is None:
return o.isoformat() + 'Z'
else:
return o.isoformat()
else:
return o.isoformat()
else:
return super(EdxJSONEncoder, self).default(o)