Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
For the long story read the tweet thread on pt 34 here https://twitter.com/KimStacks/status/1190943466492051457
"""
Helper classes for parsers.
"""
import datetime
import decimal
import json # noqa
class FromValuesToDRFJSONEncoder(json.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time/timedelta,
decimal types, generators and other basic python objects.
"""
def default(self, obj):
# For Date Time string spec, see ECMA 262
# https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
if isinstance(obj, datetime.datetime):
representation = obj.isoformat()
if representation.endswith("+00:00"):
representation = representation[:-6] + "Z"
return representation
elif isinstance(obj, decimal.Decimal):
# Serializers will coerce decimals to strings by default.
return str(obj)
return super().default(obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment