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.

36 lines
1.2 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
  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. return payload
  24. if isinstance(o, db.Model):
  25. return serialize_model(o)
  26. iterable = iter(o)
  27. except TypeError:
  28. pass
  29. else:
  30. return list(iterable)
  31. return JSONEncoder.default(self, o)