Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

encoder.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from django.db.models.query import QuerySet
  2. from django.utils import six, timezone
  3. from django.utils.encoding import force_text
  4. from django.utils.functional import Promise
  5. import datetime
  6. import decimal
  7. import json
  8. import uuid
  9. class JSONEncoder(json.JSONEncoder):
  10. """
  11. JSONEncoder subclass that knows how to encode date/time/timedelta,
  12. decimal types, generators and other basic python objects.
  13. Taken from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py
  14. """
  15. def default(self, obj): # noqa
  16. # For Date Time string spec, see ECMA 262
  17. # http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
  18. if isinstance(obj, Promise):
  19. return force_text(obj)
  20. elif isinstance(obj, datetime.datetime):
  21. representation = obj.isoformat()
  22. if obj.microsecond:
  23. representation = representation[:23] + representation[26:]
  24. if representation.endswith('+00:00'):
  25. representation = representation[:-6] + 'Z'
  26. return representation
  27. elif isinstance(obj, datetime.date):
  28. return obj.isoformat()
  29. elif isinstance(obj, datetime.time):
  30. if timezone and timezone.is_aware(obj):
  31. raise ValueError("JSON can't represent timezone-aware times.")
  32. representation = obj.isoformat()
  33. if obj.microsecond:
  34. representation = representation[:12]
  35. return representation
  36. elif isinstance(obj, datetime.timedelta):
  37. return six.text_type(obj.total_seconds())
  38. elif isinstance(obj, decimal.Decimal):
  39. # Serializers will coerce decimals to strings by default.
  40. return float(obj)
  41. elif isinstance(obj, uuid.UUID):
  42. return six.text_type(obj)
  43. elif isinstance(obj, QuerySet):
  44. return tuple(obj)
  45. elif hasattr(obj, 'tolist'):
  46. # Numpy arrays and array scalars.
  47. return obj.tolist()
  48. elif hasattr(obj, '__getitem__'):
  49. try:
  50. return dict(obj)
  51. except:
  52. pass
  53. elif hasattr(obj, '__iter__'):
  54. return tuple(item for item in obj)
  55. return super(JSONEncoder, self).default(obj)