encoders.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. Helper classes for parsers.
  3. """
  4. import datetime
  5. import decimal
  6. import json # noqa
  7. import uuid
  8. from django.db.models.query import QuerySet
  9. from django.utils import timezone
  10. from django.utils.encoding import force_str
  11. from django.utils.functional import Promise
  12. from rest_framework.compat import coreapi
  13. class JSONEncoder(json.JSONEncoder):
  14. """
  15. JSONEncoder subclass that knows how to encode date/time/timedelta,
  16. decimal types, generators and other basic python objects.
  17. """
  18. def default(self, obj):
  19. # For Date Time string spec, see ECMA 262
  20. # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
  21. if isinstance(obj, Promise):
  22. return force_str(obj)
  23. elif isinstance(obj, datetime.datetime):
  24. representation = obj.isoformat()
  25. if representation.endswith('+00:00'):
  26. representation = representation[:-6] + 'Z'
  27. return representation
  28. elif isinstance(obj, datetime.date):
  29. return obj.isoformat()
  30. elif isinstance(obj, datetime.time):
  31. if timezone and timezone.is_aware(obj):
  32. raise ValueError("JSON can't represent timezone-aware times.")
  33. representation = obj.isoformat()
  34. return representation
  35. elif isinstance(obj, datetime.timedelta):
  36. return str(obj.total_seconds())
  37. elif isinstance(obj, decimal.Decimal):
  38. # Serializers will coerce decimals to strings by default.
  39. return float(obj)
  40. elif isinstance(obj, uuid.UUID):
  41. return str(obj)
  42. elif isinstance(obj, QuerySet):
  43. return tuple(obj)
  44. elif isinstance(obj, bytes):
  45. # Best-effort for binary blobs. See #4187.
  46. return obj.decode()
  47. elif hasattr(obj, 'tolist'):
  48. # Numpy arrays and array scalars.
  49. return obj.tolist()
  50. elif (coreapi is not None) and isinstance(obj, (coreapi.Document, coreapi.Error)):
  51. raise RuntimeError(
  52. 'Cannot return a coreapi object from a JSON view. '
  53. 'You should be using a schema renderer instead for this view.'
  54. )
  55. elif hasattr(obj, '__getitem__'):
  56. cls = (list if isinstance(obj, (list, tuple)) else dict)
  57. try:
  58. return cls(obj)
  59. except Exception:
  60. pass
  61. elif hasattr(obj, '__iter__'):
  62. return tuple(item for item in obj)
  63. return super().default(obj)