30 lines
785 B
Python
30 lines
785 B
Python
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from flask.json import JSONEncoder as _FlaskJSONEncoder
|
|
|
|
__all__ = [
|
|
'JSONEncoder',
|
|
]
|
|
|
|
|
|
class JSONEncoder(_FlaskJSONEncoder):
|
|
"""
|
|
Custom JSON encoder built on top of the Flask JSONEncoder class.
|
|
"""
|
|
|
|
def default(self, obj: Any) -> Any:
|
|
"""
|
|
Convert any object to a JSON serializable type.
|
|
"""
|
|
# Convert datetimes to ISO format without microseconds (e.g. '2022-01-02T10:20:30+00:00')
|
|
if isinstance(obj, datetime):
|
|
return obj.isoformat(timespec='seconds')
|
|
|
|
# Use to_dict() method on objects that have it
|
|
if hasattr(obj, 'to_dict'):
|
|
return obj.to_dict()
|
|
|
|
# Fallback to the Flask JSONEncoder
|
|
return super().default(obj)
|