serializers.py 7.5 KB

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