1
0

serializers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. """Serializers used to convert Var types to JSON strings."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import functools
  5. import json
  6. import warnings
  7. from datetime import date, datetime, time, timedelta
  8. from enum import Enum
  9. from pathlib import Path
  10. from typing import (
  11. Any,
  12. Callable,
  13. List,
  14. Literal,
  15. Optional,
  16. Set,
  17. Tuple,
  18. Type,
  19. Union,
  20. get_type_hints,
  21. overload,
  22. )
  23. from reflex.base import Base
  24. from reflex.constants.colors import Color, format_color
  25. from reflex.utils import types
  26. # Mapping from type to a serializer.
  27. # The serializer should convert the type to a JSON object.
  28. SerializedType = Union[str, bool, int, float, list, dict, None]
  29. Serializer = Callable[[Type], SerializedType]
  30. SERIALIZERS: dict[Type, Serializer] = {}
  31. SERIALIZER_TYPES: dict[Type, Type] = {}
  32. def serializer(
  33. fn: Serializer | None = None,
  34. to: Type | None = None,
  35. ) -> Serializer:
  36. """Decorator to add a serializer for a given type.
  37. Args:
  38. fn: The function to decorate.
  39. to: The type returned by the serializer. If this is `str`, then any Var created from this type will be treated as a string.
  40. Returns:
  41. The decorated function.
  42. Raises:
  43. ValueError: If the function does not take a single argument.
  44. """
  45. if fn is None:
  46. # If the function is not provided, return a partial that acts as a decorator.
  47. return functools.partial(serializer, to=to) # type: ignore
  48. # Check the type hints to get the type of the argument.
  49. type_hints = get_type_hints(fn)
  50. args = [arg for arg in type_hints if arg != "return"]
  51. # Make sure the function takes a single argument.
  52. if len(args) != 1:
  53. raise ValueError("Serializer must take a single argument.")
  54. # Get the type of the argument.
  55. type_ = type_hints[args[0]]
  56. # Make sure the type is not already registered.
  57. registered_fn = SERIALIZERS.get(type_)
  58. if registered_fn is not None and registered_fn != fn:
  59. raise ValueError(
  60. f"Serializer for type {type_} is already registered as {registered_fn.__qualname__}."
  61. )
  62. # Apply type transformation if requested
  63. if to is not None or ((to := type_hints.get("return")) is not None):
  64. SERIALIZER_TYPES[type_] = to
  65. get_serializer_type.cache_clear()
  66. # Register the serializer.
  67. SERIALIZERS[type_] = fn
  68. get_serializer.cache_clear()
  69. # Return the function.
  70. return fn
  71. @overload
  72. def serialize(
  73. value: Any, get_type: Literal[True]
  74. ) -> Tuple[Optional[SerializedType], Optional[types.GenericType]]: ...
  75. @overload
  76. def serialize(value: Any, get_type: Literal[False]) -> Optional[SerializedType]: ...
  77. @overload
  78. def serialize(value: Any) -> Optional[SerializedType]: ...
  79. def serialize(
  80. value: Any, get_type: bool = False
  81. ) -> Union[
  82. Optional[SerializedType],
  83. Tuple[Optional[SerializedType], Optional[types.GenericType]],
  84. ]:
  85. """Serialize the value to a JSON string.
  86. Args:
  87. value: The value to serialize.
  88. get_type: Whether to return the type of the serialized value.
  89. Returns:
  90. The serialized value, or None if a serializer is not found.
  91. """
  92. # Get the serializer for the type.
  93. serializer = get_serializer(type(value))
  94. # If there is no serializer, return None.
  95. if serializer is None:
  96. if dataclasses.is_dataclass(value) and not isinstance(value, type):
  97. return {k.name: getattr(value, k.name) for k in dataclasses.fields(value)}
  98. if get_type:
  99. return None, None
  100. return None
  101. # Serialize the value.
  102. serialized = serializer(value)
  103. # Return the serialized value and the type.
  104. if get_type:
  105. return serialized, get_serializer_type(type(value))
  106. else:
  107. return serialized
  108. @functools.lru_cache
  109. def get_serializer(type_: Type) -> Optional[Serializer]:
  110. """Get the serializer for the type.
  111. Args:
  112. type_: The type to get the serializer for.
  113. Returns:
  114. The serializer for the type, or None if there is no serializer.
  115. """
  116. # First, check if the type is registered.
  117. serializer = SERIALIZERS.get(type_)
  118. if serializer is not None:
  119. return serializer
  120. # If the type is not registered, check if it is a subclass of a registered type.
  121. for registered_type, serializer in reversed(SERIALIZERS.items()):
  122. if types._issubclass(type_, registered_type):
  123. return serializer
  124. # If there is no serializer, return None.
  125. return None
  126. @functools.lru_cache
  127. def get_serializer_type(type_: Type) -> Optional[Type]:
  128. """Get the converted type for the type after serializing.
  129. Args:
  130. type_: The type to get the serializer type for.
  131. Returns:
  132. The serialized type for the type, or None if there is no type conversion registered.
  133. """
  134. # First, check if the type is registered.
  135. serializer = SERIALIZER_TYPES.get(type_)
  136. if serializer is not None:
  137. return serializer
  138. # If the type is not registered, check if it is a subclass of a registered type.
  139. for registered_type, serializer in reversed(SERIALIZER_TYPES.items()):
  140. if types._issubclass(type_, registered_type):
  141. return serializer
  142. # If there is no serializer, return None.
  143. return None
  144. def has_serializer(type_: Type, into_type: Type | None = None) -> bool:
  145. """Check if there is a serializer for the type.
  146. Args:
  147. type_: The type to check.
  148. into_type: The type to serialize into.
  149. Returns:
  150. Whether there is a serializer for the type.
  151. """
  152. serializer_for_type = get_serializer(type_)
  153. return serializer_for_type is not None and (
  154. into_type is None or get_serializer_type(type_) == into_type
  155. )
  156. def can_serialize(type_: Type, into_type: Type | None = None) -> bool:
  157. """Check if there is a serializer for the type.
  158. Args:
  159. type_: The type to check.
  160. into_type: The type to serialize into.
  161. Returns:
  162. Whether there is a serializer for the type.
  163. """
  164. return has_serializer(type_, into_type) or (
  165. isinstance(type_, type)
  166. and dataclasses.is_dataclass(type_)
  167. and (into_type is None or into_type is dict)
  168. )
  169. @serializer(to=str)
  170. def serialize_type(value: type) -> str:
  171. """Serialize a python type.
  172. Args:
  173. value: the type to serialize.
  174. Returns:
  175. The serialized type.
  176. """
  177. return value.__name__
  178. @serializer(to=dict)
  179. def serialize_base(value: Base) -> dict:
  180. """Serialize a Base instance.
  181. Args:
  182. value : The Base to serialize.
  183. Returns:
  184. The serialized Base.
  185. """
  186. return {k: v for k, v in value.dict().items() if not callable(v)}
  187. @serializer
  188. def serialize_set(value: Set) -> list:
  189. """Serialize a set to a JSON serializable list.
  190. Args:
  191. value: The set to serialize.
  192. Returns:
  193. The serialized list.
  194. """
  195. return list(value)
  196. @serializer(to=str)
  197. def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
  198. """Serialize a datetime to a JSON string.
  199. Args:
  200. dt: The datetime to serialize.
  201. Returns:
  202. The serialized datetime.
  203. """
  204. return str(dt)
  205. @serializer(to=str)
  206. def serialize_path(path: Path) -> str:
  207. """Serialize a pathlib.Path to a JSON string.
  208. Args:
  209. path: The path to serialize.
  210. Returns:
  211. The serialized path.
  212. """
  213. return str(path.as_posix())
  214. @serializer
  215. def serialize_enum(en: Enum) -> str:
  216. """Serialize a enum to a JSON string.
  217. Args:
  218. en: The enum to serialize.
  219. Returns:
  220. The serialized enum.
  221. """
  222. return en.value
  223. @serializer(to=str)
  224. def serialize_color(color: Color) -> str:
  225. """Serialize a color.
  226. Args:
  227. color: The color to serialize.
  228. Returns:
  229. The serialized color.
  230. """
  231. return format_color(color.color, color.shade, color.alpha)
  232. try:
  233. from pandas import DataFrame
  234. def format_dataframe_values(df: DataFrame) -> List[List[Any]]:
  235. """Format dataframe values to a list of lists.
  236. Args:
  237. df: The dataframe to format.
  238. Returns:
  239. The dataframe as a list of lists.
  240. """
  241. return [
  242. [str(d) if isinstance(d, (list, tuple)) else d for d in data]
  243. for data in list(df.values.tolist())
  244. ]
  245. @serializer
  246. def serialize_dataframe(df: DataFrame) -> dict:
  247. """Serialize a pandas dataframe.
  248. Args:
  249. df: The dataframe to serialize.
  250. Returns:
  251. The serialized dataframe.
  252. """
  253. return {
  254. "columns": df.columns.tolist(),
  255. "data": format_dataframe_values(df),
  256. }
  257. except ImportError:
  258. pass
  259. try:
  260. from plotly.graph_objects import Figure, layout
  261. from plotly.io import to_json
  262. @serializer
  263. def serialize_figure(figure: Figure) -> dict:
  264. """Serialize a plotly figure.
  265. Args:
  266. figure: The figure to serialize.
  267. Returns:
  268. The serialized figure.
  269. """
  270. return json.loads(str(to_json(figure)))
  271. @serializer
  272. def serialize_template(template: layout.Template) -> dict:
  273. """Serialize a plotly template.
  274. Args:
  275. template: The template to serialize.
  276. Returns:
  277. The serialized template.
  278. """
  279. return {
  280. "data": json.loads(str(to_json(template.data))),
  281. "layout": json.loads(str(to_json(template.layout))),
  282. }
  283. except ImportError:
  284. pass
  285. try:
  286. import base64
  287. import io
  288. from PIL.Image import MIME
  289. from PIL.Image import Image as Img
  290. @serializer
  291. def serialize_image(image: Img) -> str:
  292. """Serialize a plotly figure.
  293. Args:
  294. image: The image to serialize.
  295. Returns:
  296. The serialized image.
  297. """
  298. buff = io.BytesIO()
  299. image_format = getattr(image, "format", None) or "PNG"
  300. image.save(buff, format=image_format)
  301. image_bytes = buff.getvalue()
  302. base64_image = base64.b64encode(image_bytes).decode("utf-8")
  303. try:
  304. # Newer method to get the mime type, but does not always work.
  305. mime_type = image.get_format_mimetype() # type: ignore
  306. except AttributeError:
  307. try:
  308. # Fallback method
  309. mime_type = MIME[image_format]
  310. except KeyError:
  311. # Unknown mime_type: warn and return image/png and hope the browser can sort it out.
  312. warnings.warn( # noqa: B028
  313. f"Unknown mime type for {image} {image_format}. Defaulting to image/png"
  314. )
  315. mime_type = "image/png"
  316. return f"data:{mime_type};base64,{base64_image}"
  317. except ImportError:
  318. pass