serializers.py 11 KB

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