json.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. from __future__ import annotations
  12. import typing as t
  13. from abc import ABC, abstractmethod
  14. from datetime import date, datetime, time, timedelta
  15. from json import JSONEncoder
  16. from pathlib import Path
  17. import numpy
  18. import pandas
  19. from flask.json.provider import DefaultJSONProvider
  20. from .._warnings import _warn
  21. from ..icon import Icon
  22. from ..utils import _date_to_string, _MapDict, _TaipyBase
  23. from ..utils.singleton import _Singleton
  24. class JsonAdapter(ABC):
  25. def register(self):
  26. _TaipyJsonAdapter().register(self)
  27. @abstractmethod
  28. def parse(self, o) -> t.Union[t.Any, None]:
  29. return None
  30. class _DefaultJsonAdapter(JsonAdapter):
  31. def parse(self, o):
  32. if isinstance(o, Icon):
  33. return o._to_dict()
  34. if isinstance(o, _MapDict):
  35. return o._dict
  36. if isinstance(o, _TaipyBase):
  37. return o.get()
  38. if isinstance(o, (datetime, date, time)):
  39. return _date_to_string(o)
  40. if isinstance(o, Path):
  41. return str(o)
  42. if isinstance(o, (timedelta, pandas.Timedelta)):
  43. return str(o)
  44. if isinstance(o, numpy.generic):
  45. return getattr(o, "tolist", lambda: o)()
  46. class _TaipyJsonAdapter(object, metaclass=_Singleton):
  47. def __init__(self) -> None:
  48. self._adapters: t.List[JsonAdapter] = []
  49. self.register(_DefaultJsonAdapter())
  50. def register(self, adapter: JsonAdapter):
  51. self._adapters.append(adapter)
  52. def parse(self, o):
  53. try:
  54. for adapter in reversed(self._adapters):
  55. if (output := adapter.parse(o)) is not None:
  56. return output
  57. raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable (value: {o}).")
  58. except Exception as e:
  59. _warn("Exception while resolving JSON", e)
  60. return None
  61. class _TaipyJsonEncoder(JSONEncoder):
  62. def default(self, o):
  63. return _TaipyJsonAdapter().parse(o)
  64. class _TaipyJsonProvider(DefaultJSONProvider):
  65. default = staticmethod(_TaipyJsonAdapter().parse) # type: ignore
  66. sort_keys = False