Skip to content

Instantly share code, notes, and snippets.

@simkimsia
Created November 3, 2019 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simkimsia/ab96a26bcb3a735fa416c33d75e576db to your computer and use it in GitHub Desktop.
Save simkimsia/ab96a26bcb3a735fa416c33d75e576db to your computer and use it in GitHub Desktop.
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