serializers.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. """Serializers used to convert Var types to JSON strings."""
  2. from __future__ import annotations
  3. import json
  4. import types as builtin_types
  5. from datetime import date, datetime, time, timedelta
  6. from typing import Any, Callable, Dict, List, Set, Tuple, Type, Union, get_type_hints
  7. from reflex.base import Base
  8. from reflex.constants.colors import Color, format_color
  9. from reflex.utils import exceptions, format, types
  10. # Mapping from type to a serializer.
  11. # The serializer should convert the type to a JSON object.
  12. SerializedType = Union[str, bool, int, float, list, dict]
  13. Serializer = Callable[[Type], SerializedType]
  14. SERIALIZERS: dict[Type, Serializer] = {}
  15. def serializer(fn: Serializer) -> Serializer:
  16. """Decorator to add a serializer for a given type.
  17. Args:
  18. fn: The function to decorate.
  19. Returns:
  20. The decorated function.
  21. Raises:
  22. ValueError: If the function does not take a single argument.
  23. """
  24. # Get the global serializers.
  25. global SERIALIZERS
  26. # Check the type hints to get the type of the argument.
  27. type_hints = get_type_hints(fn)
  28. args = [arg for arg in type_hints if arg != "return"]
  29. # Make sure the function takes a single argument.
  30. if len(args) != 1:
  31. raise ValueError("Serializer must take a single argument.")
  32. # Get the type of the argument.
  33. type_ = type_hints[args[0]]
  34. # Make sure the type is not already registered.
  35. registered_fn = SERIALIZERS.get(type_)
  36. if registered_fn is not None and registered_fn != fn:
  37. raise ValueError(
  38. f"Serializer for type {type_} is already registered as {registered_fn.__qualname__}."
  39. )
  40. # Register the serializer.
  41. SERIALIZERS[type_] = fn
  42. # Return the function.
  43. return fn
  44. def serialize(value: Any) -> SerializedType | None:
  45. """Serialize the value to a JSON string.
  46. Args:
  47. value: The value to serialize.
  48. Returns:
  49. The serialized value, or None if a serializer is not found.
  50. """
  51. # Get the serializer for the type.
  52. serializer = get_serializer(type(value))
  53. # If there is no serializer, return None.
  54. if serializer is None:
  55. return None
  56. # Serialize the value.
  57. return serializer(value)
  58. def get_serializer(type_: Type) -> Serializer | None:
  59. """Get the serializer for the type.
  60. Args:
  61. type_: The type to get the serializer for.
  62. Returns:
  63. The serializer for the type, or None if there is no serializer.
  64. """
  65. global SERIALIZERS
  66. # First, check if the type is registered.
  67. serializer = SERIALIZERS.get(type_)
  68. if serializer is not None:
  69. return serializer
  70. # If the type is not registered, check if it is a subclass of a registered type.
  71. for registered_type, serializer in reversed(SERIALIZERS.items()):
  72. if types._issubclass(type_, registered_type):
  73. return serializer
  74. # If there is no serializer, return None.
  75. return None
  76. def has_serializer(type_: Type) -> bool:
  77. """Check if there is a serializer for the type.
  78. Args:
  79. type_: The type to check.
  80. Returns:
  81. Whether there is a serializer for the type.
  82. """
  83. return get_serializer(type_) is not None
  84. @serializer
  85. def serialize_type(value: type) -> str:
  86. """Serialize a python type.
  87. Args:
  88. value: the type to serialize.
  89. Returns:
  90. The serialized type.
  91. """
  92. return value.__name__
  93. @serializer
  94. def serialize_str(value: str) -> str:
  95. """Serialize a string.
  96. Args:
  97. value: The string to serialize.
  98. Returns:
  99. The serialized string.
  100. """
  101. return value
  102. @serializer
  103. def serialize_primitive(value: Union[bool, int, float, None]) -> str:
  104. """Serialize a primitive type.
  105. Args:
  106. value: The number/bool/None to serialize.
  107. Returns:
  108. The serialized number/bool/None.
  109. """
  110. return format.json_dumps(value)
  111. @serializer
  112. def serialize_base(value: Base) -> str:
  113. """Serialize a Base instance.
  114. Args:
  115. value : The Base to serialize.
  116. Returns:
  117. The serialized Base.
  118. """
  119. return value.json()
  120. @serializer
  121. def serialize_list(value: Union[List, Tuple, Set]) -> str:
  122. """Serialize a list to a JSON string.
  123. Args:
  124. value: The list to serialize.
  125. Returns:
  126. The serialized list.
  127. """
  128. # Dump the list to a string.
  129. fprop = format.json_dumps(list(value))
  130. # Unwrap var values.
  131. return format.unwrap_vars(fprop)
  132. @serializer
  133. def serialize_dict(prop: Dict[str, Any]) -> str:
  134. """Serialize a dictionary to a JSON string.
  135. Args:
  136. prop: The dictionary to serialize.
  137. Returns:
  138. The serialized dictionary.
  139. Raises:
  140. InvalidStylePropError: If the style prop is invalid.
  141. """
  142. # Import here to avoid circular imports.
  143. from reflex.event import EventHandler
  144. prop_dict = {}
  145. for key, value in prop.items():
  146. if types._issubclass(type(value), Callable):
  147. raise exceptions.InvalidStylePropError(
  148. f"The style prop `{format.to_snake_case(key)}` cannot have " # type: ignore
  149. f"`{value.fn.__qualname__ if isinstance(value, EventHandler) else value.__qualname__ if isinstance(value, builtin_types.FunctionType) else value}`, "
  150. f"an event handler or callable as its value"
  151. )
  152. prop_dict[key] = value
  153. # Dump the dict to a string.
  154. fprop = format.json_dumps(prop_dict)
  155. # Unwrap var values.
  156. return format.unwrap_vars(fprop)
  157. @serializer
  158. def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
  159. """Serialize a datetime to a JSON string.
  160. Args:
  161. dt: The datetime to serialize.
  162. Returns:
  163. The serialized datetime.
  164. """
  165. return str(dt)
  166. @serializer
  167. def serialize_color(color: Color) -> str:
  168. """Serialize a color.
  169. Args:
  170. color: The color to serialize.
  171. Returns:
  172. The serialized color.
  173. """
  174. return format_color(color.color, color.shade, color.alpha)
  175. try:
  176. from pandas import DataFrame
  177. def format_dataframe_values(df: DataFrame) -> List[List[Any]]:
  178. """Format dataframe values to a list of lists.
  179. Args:
  180. df: The dataframe to format.
  181. Returns:
  182. The dataframe as a list of lists.
  183. """
  184. return [
  185. [str(d) if isinstance(d, (list, tuple)) else d for d in data]
  186. for data in list(df.values.tolist())
  187. ]
  188. @serializer
  189. def serialize_dataframe(df: DataFrame) -> dict:
  190. """Serialize a pandas dataframe.
  191. Args:
  192. df: The dataframe to serialize.
  193. Returns:
  194. The serialized dataframe.
  195. """
  196. return {
  197. "columns": df.columns.tolist(),
  198. "data": format_dataframe_values(df),
  199. }
  200. except ImportError:
  201. pass
  202. try:
  203. from plotly.graph_objects import Figure
  204. from plotly.io import to_json
  205. @serializer
  206. def serialize_figure(figure: Figure) -> list:
  207. """Serialize a plotly figure.
  208. Args:
  209. figure: The figure to serialize.
  210. Returns:
  211. The serialized figure.
  212. """
  213. return json.loads(str(to_json(figure)))["data"]
  214. except ImportError:
  215. pass
  216. try:
  217. import base64
  218. import io
  219. from PIL.Image import Image as Img
  220. @serializer
  221. def serialize_image(image: Img) -> str:
  222. """Serialize a plotly figure.
  223. Args:
  224. image: The image to serialize.
  225. Returns:
  226. The serialized image.
  227. """
  228. buff = io.BytesIO()
  229. image.save(buff, format=getattr(image, "format", None) or "PNG")
  230. image_bytes = buff.getvalue()
  231. base64_image = base64.b64encode(image_bytes).decode("utf-8")
  232. mime_type = getattr(image, "get_format_mimetype", lambda: "image/png")()
  233. return f"data:{mime_type};base64,{base64_image}"
  234. except ImportError:
  235. pass