serializers.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 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_str(value: str) -> str:
  84. """Serialize a string.
  85. Args:
  86. value: The string to serialize.
  87. Returns:
  88. The serialized string.
  89. """
  90. return value
  91. @serializer
  92. def serialize_primitive(value: Union[bool, int, float, Base, None]) -> str:
  93. """Serialize a primitive type.
  94. Args:
  95. value: The number to serialize.
  96. Returns:
  97. The serialized number.
  98. """
  99. return format.json_dumps(value)
  100. @serializer
  101. def serialize_list(value: Union[List, Tuple, Set]) -> str:
  102. """Serialize a list to a JSON string.
  103. Args:
  104. value: The list to serialize.
  105. Returns:
  106. The serialized list.
  107. """
  108. from reflex.vars import Var
  109. # Convert any var values to strings.
  110. fprop = format.json_dumps([str(v) if isinstance(v, Var) else v for v in value])
  111. # Unwrap var values.
  112. return format.unwrap_vars(fprop)
  113. @serializer
  114. def serialize_dict(prop: Dict[str, Any]) -> str:
  115. """Serialize a dictionary to a JSON string.
  116. Args:
  117. prop: The dictionary to serialize.
  118. Returns:
  119. The serialized dictionary.
  120. Raises:
  121. InvalidStylePropError: If the style prop is invalid.
  122. """
  123. # Import here to avoid circular imports.
  124. from reflex.event import EventHandler
  125. from reflex.vars import Var
  126. prop_dict = {}
  127. # Convert any var keys to strings.
  128. for key, value in prop.items():
  129. if types._issubclass(type(value), Callable):
  130. raise exceptions.InvalidStylePropError(
  131. f"The style prop `{format.to_snake_case(key)}` cannot have " # type: ignore
  132. f"`{value.fn.__qualname__ if isinstance(value, EventHandler) else value.__qualname__ if isinstance(value, builtin_types.FunctionType) else value}`, "
  133. f"an event handler or callable as its value"
  134. )
  135. prop_dict[key] = str(value) if isinstance(value, Var) else value
  136. # Dump the dict to a string.
  137. fprop = format.json_dumps(prop_dict)
  138. # Unwrap var values.
  139. return format.unwrap_vars(fprop)
  140. @serializer
  141. def serialize_datetime(dt: Union[date, datetime, time, timedelta]) -> str:
  142. """Serialize a datetime to a JSON string.
  143. Args:
  144. dt: The datetime to serialize.
  145. Returns:
  146. The serialized datetime.
  147. """
  148. return str(dt)