An ebook/comic library service and web client
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.

38 lines
1.3 KiB

  1. """JSON specific utilities."""
  2. from datetime import date
  3. from typing import Any
  4. import rfc3339
  5. from flask.json import JSONEncoder
  6. from atheneum.api.model import APIResponse, APIMessage
  7. from atheneum.db import db
  8. from atheneum.errors import BaseError
  9. from atheneum.service.transformation_service import serialize_model
  10. class CustomJSONEncoder(JSONEncoder):
  11. """Ensure that datetime values are serialized correctly."""
  12. def default(self, o: Any) -> Any: # pylint: disable=E0202,R0911
  13. """Handle encoding date and datetime objects according to rfc3339."""
  14. try:
  15. if isinstance(o, date):
  16. return rfc3339.format(o)
  17. if isinstance(o, APIResponse):
  18. payload = o.payload
  19. if isinstance(payload, db.Model):
  20. return serialize_model(o.payload, o.options)
  21. if isinstance(payload, BaseError):
  22. return payload.to_dict()
  23. if isinstance(payload, APIMessage):
  24. return payload.to_dict()
  25. return payload
  26. if isinstance(o, db.Model):
  27. return serialize_model(o)
  28. iterable = iter(o)
  29. except TypeError:
  30. pass
  31. else:
  32. return list(iterable)
  33. return JSONEncoder.default(self, o)