serializers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. """Serializers used to convert Var types to JSON strings."""
  2. from __future__ import annotations
  3. import functools
  4. import json
  5. import warnings
  6. from datetime import date, datetime, time, timedelta
  7. from enum import Enum
  8. from pathlib import Path
  9. from typing import (
  10. Any,
  11. Callable,
  12. Dict,
  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]
  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:
  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 get_type:
  97. return None, None
  98. return None
  99. # Serialize the value.
  100. serialized = serializer(value)
  101. # Return the serialized value and the type.
  102. if get_type:
  103. return serialized, get_serializer_type(type(value))
  104. else:
  105. return serialized
  106. @functools.lru_cache
  107. def get_serializer(type_: Type) -> Optional[Serializer]:
  108. """Get the serializer for the type.
  109. Args:
  110. type_: The type to get the serializer for.
  111. Returns:
  112. The serializer for the type, or None if there is no serializer.
  113. """
  114. # First, check if the type is registered.
  115. serializer = SERIALIZERS.get(type_)
  116. if serializer is not None:
  117. return serializer
  118. # If the type is not registered, check if it is a subclass of a registered type.
  119. for registered_type, serializer in reversed(SERIALIZERS.items()):
  120. if types._issubclass(type_, registered_type):
  121. return serializer
  122. # If there is no serializer, return None.
  123. return None
  124. @functools.lru_cache
  125. def get_serializer_type(type_: Type) -> Optional[Type]:
  126. """Get the converted type for the type after serializing.
  127. Args:
  128. type_: The type to get the serializer type for.
  129. Returns:
  130. The serialized type for the type, or None if there is no type conversion registered.
  131. """
  132. # First, check if the type is registered.
  133. serializer = SERIALIZER_TYPES.get(type_)
  134. if serializer is not None:
  135. return serializer
  136. # If the type is not registered, check if it is a subclass of a registered type.
  137. for registered_type, serializer in reversed(SERIALIZER_TYPES.items()):
  138. if types._issubclass(type_, registered_type):
  139. return serializer
  140. # If there is no serializer, return None.
  141. return None
  142. def has_serializer(type_: Type) -> bool:
  143. """Check if there is a serializer for the type.
  144. Args:
  145. type_: The type to check.
  146. Returns:
  147. Whether there is a serializer for the type.
  148. """
  149. return get_serializer(type_) is not None
  150. @serializer(to=str)
  151. def serialize_type(value: type) -> str:
  152. """Serialize a python type.
  153. Args:
  154. value: the type to serialize.
  155. Returns:
  156. The serialized type.
  157. """
  158. return value.__name__
  159. @serializer
  160. def serialize_str(value: str) -> str:
  161. """Serialize a string.
  162. Args:
  163. value: The string to serialize.
  164. Returns:
  165. The serialized string.
  166. """
  167. return value
  168. @serializer
  169. def serialize_primitive(value: Union[bool, int, float, None]) -> str:
  170. """Serialize a primitive type.
  171. Args:
  172. value: The number/bool/None to serialize.
  173. Returns:
  174. The serialized number/bool/None.
  175. """
  176. from reflex.utils import format
  177. return format.json_dumps(value)
  178. @serializer
  179. def serialize_base(value: Base) -> str:
  180. """Serialize a Base instance.
  181. Args:
  182. value : The Base to serialize.
  183. Returns:
  184. The serialized Base.
  185. """
  186. from reflex.vars import LiteralVar
  187. return str(LiteralVar.create(value))
  188. @serializer
  189. def serialize_list(value: Union[List, Tuple, Set]) -> str:
  190. """Serialize a list to a JSON string.
  191. Args:
  192. value: The list to serialize.
  193. Returns:
  194. The serialized list.
  195. """
  196. from reflex.vars import LiteralArrayVar
  197. return str(LiteralArrayVar.create(value))
  198. @serializer
  199. def serialize_dict(prop: Dict[str, Any]) -> str:
  200. """Serialize a dictionary to a JSON string.
  201. Args:
  202. prop: The dictionary to serialize.
  203. Returns:
  204. The serialized dictionary.
  205. """
  206. from reflex.vars import LiteralObjectVar
  207. return str(LiteralObjectVar.create(prop))
  208. @serializer(to=str)
  209. def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
  210. """Serialize a datetime to a JSON string.
  211. Args:
  212. dt: The datetime to serialize.
  213. Returns:
  214. The serialized datetime.
  215. """
  216. return str(dt)
  217. @serializer(to=str)
  218. def serialize_path(path: Path) -> str:
  219. """Serialize a pathlib.Path to a JSON string.
  220. Args:
  221. path: The path to serialize.
  222. Returns:
  223. The serialized path.
  224. """
  225. return str(path.as_posix())
  226. @serializer
  227. def serialize_enum(en: Enum) -> str:
  228. """Serialize a enum to a JSON string.
  229. Args:
  230. en: The enum to serialize.
  231. Returns:
  232. The serialized enum.
  233. """
  234. return en.value
  235. @serializer(to=str)
  236. def serialize_color(color: Color) -> str:
  237. """Serialize a color.
  238. Args:
  239. color: The color to serialize.
  240. Returns:
  241. The serialized color.
  242. """
  243. return format_color(color.color, color.shade, color.alpha)
  244. try:
  245. from pandas import DataFrame
  246. def format_dataframe_values(df: DataFrame) -> List[List[Any]]:
  247. """Format dataframe values to a list of lists.
  248. Args:
  249. df: The dataframe to format.
  250. Returns:
  251. The dataframe as a list of lists.
  252. """
  253. return [
  254. [str(d) if isinstance(d, (list, tuple)) else d for d in data]
  255. for data in list(df.values.tolist())
  256. ]
  257. @serializer
  258. def serialize_dataframe(df: DataFrame) -> dict:
  259. """Serialize a pandas dataframe.
  260. Args:
  261. df: The dataframe to serialize.
  262. Returns:
  263. The serialized dataframe.
  264. """
  265. return {
  266. "columns": df.columns.tolist(),
  267. "data": format_dataframe_values(df),
  268. }
  269. except ImportError:
  270. pass
  271. try:
  272. from plotly.graph_objects import Figure, layout
  273. from plotly.io import to_json
  274. @serializer
  275. def serialize_figure(figure: Figure) -> dict:
  276. """Serialize a plotly figure.
  277. Args:
  278. figure: The figure to serialize.
  279. Returns:
  280. The serialized figure.
  281. """
  282. return json.loads(str(to_json(figure)))
  283. @serializer
  284. def serialize_template(template: layout.Template) -> dict:
  285. """Serialize a plotly template.
  286. Args:
  287. template: The template to serialize.
  288. Returns:
  289. The serialized template.
  290. """
  291. return {
  292. "data": json.loads(str(to_json(template.data))),
  293. "layout": json.loads(str(to_json(template.layout))),
  294. }
  295. except ImportError:
  296. pass
  297. try:
  298. import base64
  299. import io
  300. from PIL.Image import MIME
  301. from PIL.Image import Image as Img
  302. @serializer
  303. def serialize_image(image: Img) -> str:
  304. """Serialize a plotly figure.
  305. Args:
  306. image: The image to serialize.
  307. Returns:
  308. The serialized image.
  309. """
  310. buff = io.BytesIO()
  311. image_format = getattr(image, "format", None) or "PNG"
  312. image.save(buff, format=image_format)
  313. image_bytes = buff.getvalue()
  314. base64_image = base64.b64encode(image_bytes).decode("utf-8")
  315. try:
  316. # Newer method to get the mime type, but does not always work.
  317. mime_type = image.get_format_mimetype() # type: ignore
  318. except AttributeError:
  319. try:
  320. # Fallback method
  321. mime_type = MIME[image_format]
  322. except KeyError:
  323. # Unknown mime_type: warn and return image/png and hope the browser can sort it out.
  324. warnings.warn( # noqa: B028
  325. f"Unknown mime type for {image} {image_format}. Defaulting to image/png"
  326. )
  327. mime_type = "image/png"
  328. return f"data:{mime_type};base64,{base64_image}"
  329. except ImportError:
  330. pass