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.

27 lines
811 B

  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.db import db
  7. from atheneum.service.transformation_service import serialize_model
  8. class CustomJSONEncoder(JSONEncoder):
  9. """Ensure that datetime values are serialized correctly."""
  10. def default(self, o: Any) -> Any: # pylint: disable=E0202
  11. """Handle encoding date and datetime objects according to rfc3339."""
  12. try:
  13. if isinstance(o, date):
  14. return rfc3339.format(o)
  15. if isinstance(o, db.Model):
  16. return serialize_model(o)
  17. iterable = iter(o)
  18. except TypeError:
  19. pass
  20. else:
  21. return list(iterable)
  22. return JSONEncoder.default(self, o)