serializers.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. """Serializers used to convert Var types to JSON strings."""
  2. from __future__ import annotations
  3. import types as builtin_types
  4. from datetime import date, datetime, time, timedelta
  5. from typing import Any, Callable, Dict, List, Set, Tuple, Type, Union, get_type_hints
  6. from reflex.base import Base
  7. from reflex.utils import exceptions, format, types
  8. # Mapping from type to a serializer.
  9. # The serializer should convert the type to a JSON object.
  10. SerializedType = Union[str, bool, int, float, list, dict]
  11. Serializer = Callable[[Type], SerializedType]
  12. SERIALIZERS: dict[Type, Serializer] = {}
  13. def serializer(fn: Serializer) -> Serializer:
  14. """Decorator to add a serializer for a given type.
  15. Args:
  16. fn: The function to decorate.
  17. Returns:
  18. The decorated function.
  19. Raises:
  20. ValueError: If the function does not take a single argument.
  21. """
  22. # Get the global serializers.
  23. global SERIALIZERS
  24. # Check the type hints to get the type of the argument.
  25. type_hints = get_type_hints(fn)
  26. args = [arg for arg in type_hints if arg != "return"]
  27. # Make sure the function takes a single argument.
  28. if len(args) != 1:
  29. raise ValueError("Serializer must take a single argument.")
  30. # Get the type of the argument.
  31. type_ = type_hints[args[0]]
  32. # Make sure the type is not already registered.
  33. registered_fn = SERIALIZERS.get(type_)
  34. if registered_fn is not None and registered_fn != fn:
  35. raise ValueError(
  36. f"Serializer for type {type_} is already registered as {registered_fn.__qualname__}."
  37. )
  38. # Register the serializer.
  39. SERIALIZERS[type_] = fn
  40. # Return the function.
  41. return fn
  42. def serialize(value: Any) -> SerializedType | None:
  43. """Serialize the value to a JSON string.
  44. Args:
  45. value: The value to serialize.
  46. Returns:
  47. The serialized value, or None if a serializer is not found.
  48. """
  49. # Get the serializer for the type.
  50. serializer = get_serializer(type(value))
  51. # If there is no serializer, return None.
  52. if serializer is None:
  53. return None
  54. # Serialize the value.
  55. return serializer(value)
  56. def get_serializer(type_: Type) -> Serializer | None:
  57. """Get the serializer for the type.
  58. Args:
  59. type_: The type to get the serializer for.
  60. Returns:
  61. The serializer for the type, or None if there is no serializer.
  62. """
  63. global SERIALIZERS
  64. # First, check if the type is registered.
  65. serializer = SERIALIZERS.get(type_)
  66. if serializer is not None:
  67. return serializer
  68. # If the type is not registered, check if it is a subclass of a registered type.
  69. for registered_type, serializer in reversed(SERIALIZERS.items()):
  70. if types._issubclass(type_, registered_type):
  71. return serializer
  72. # If there is no serializer, return None.
  73. return None
  74. def has_serializer(type_: Type) -> bool:
  75. """Check if there is a serializer for the type.
  76. Args:
  77. type_: The type to check.
  78. Returns:
  79. Whether there is a serializer for the type.
  80. """
  81. return get_serializer(type_) is not None
  82. @serializer
  83. def serialize_type(value: type) -> str:
  84. """Serialize a python type.
  85. Args:
  86. value: the type to serialize.
  87. Returns:
  88. The serialized type.
  89. """
  90. return value.__name__
  91. @serializer
  92. def serialize_str(value: str) -> str:
  93. """Serialize a string.
  94. Args:
  95. value: The string to serialize.
  96. Returns:
  97. The serialized string.
  98. """
  99. return value
  100. @serializer
  101. def serialize_primitive(value: Union[bool, int, float, None]) -> str:
  102. """Serialize a primitive type.
  103. Args:
  104. value: The number/bool/None to serialize.
  105. Returns:
  106. The serialized number/bool/None.
  107. """
  108. return format.json_dumps(value)
  109. @serializer
  110. def serialize_base(value: Base) -> str:
  111. """Serialize a Base instance.
  112. Args:
  113. value : The Base to serialize.
  114. Returns:
  115. The serialized Base.
  116. """
  117. return value.json()
  118. @serializer
  119. def serialize_list(value: Union[List, Tuple, Set]) -> str:
  120. """Serialize a list to a JSON string.
  121. Args:
  122. value: The list to serialize.
  123. Returns:
  124. The serialized list.
  125. """
  126. from reflex.vars import Var
  127. # Convert any var values to strings.
  128. fprop = format.json_dumps([str(v) if isinstance(v, Var) else v for v in 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. from reflex.vars import Var
  144. prop_dict = {}
  145. # Convert any var keys to strings.
  146. for key, value in prop.items():
  147. if types._issubclass(type(value), Callable):
  148. raise exceptions.InvalidStylePropError(
  149. f"The style prop `{format.to_snake_case(key)}` cannot have " # type: ignore
  150. f"`{value.fn.__qualname__ if isinstance(value, EventHandler) else value.__qualname__ if isinstance(value, builtin_types.FunctionType) else value}`, "
  151. f"an event handler or callable as its value"
  152. )
  153. prop_dict[key] = str(value) if isinstance(value, Var) else value
  154. # Dump the dict to a string.
  155. fprop = format.json_dumps(prop_dict)
  156. # Unwrap var values.
  157. return format.unwrap_vars(fprop)
  158. @serializer
  159. def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
  160. """Serialize a datetime to a JSON string.
  161. Args:
  162. dt: The datetime to serialize.
  163. Returns:
  164. The serialized datetime.
  165. """
  166. return str(dt)