base.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. """Define the base Reflex class."""
  2. from __future__ import annotations
  3. import os
  4. from typing import TYPE_CHECKING, Any, List, Type
  5. try:
  6. import pydantic.v1.main as pydantic_main
  7. from pydantic.v1 import BaseModel
  8. from pydantic.v1.fields import ModelField
  9. except ModuleNotFoundError:
  10. if not TYPE_CHECKING:
  11. import pydantic.main as pydantic_main
  12. from pydantic import BaseModel
  13. from pydantic.fields import ModelField # type: ignore
  14. from reflex import constants
  15. def validate_field_name(bases: List[Type["BaseModel"]], field_name: str) -> None:
  16. """Ensure that the field's name does not shadow an existing attribute of the model.
  17. Args:
  18. bases: List of base models to check for shadowed attrs.
  19. field_name: name of attribute
  20. Raises:
  21. VarNameError: If state var field shadows another in its parent state
  22. """
  23. from reflex.utils.exceptions import VarNameError
  24. reload = os.getenv(constants.RELOAD_CONFIG) == "True"
  25. for base in bases:
  26. try:
  27. if not reload and getattr(base, field_name, None):
  28. pass
  29. except TypeError as te:
  30. raise VarNameError(
  31. f'State var "{field_name}" in {base} has been shadowed by a substate var; '
  32. f'use a different field name instead".'
  33. ) from te
  34. # monkeypatch pydantic validate_field_name method to skip validating
  35. # shadowed state vars when reloading app via utils.prerequisites.get_app(reload=True)
  36. pydantic_main.validate_field_name = validate_field_name # type: ignore
  37. class Base(BaseModel): # pyright: ignore [reportUnboundVariable]
  38. """The base class subclassed by all Reflex classes.
  39. This class wraps Pydantic and provides common methods such as
  40. serialization and setting fields.
  41. Any data structure that needs to be transferred between the
  42. frontend and backend should subclass this class.
  43. """
  44. class Config:
  45. """Pydantic config."""
  46. arbitrary_types_allowed = True
  47. use_enum_values = True
  48. extra = "allow"
  49. def json(self) -> str:
  50. """Convert the object to a json string.
  51. Returns:
  52. The object as a json string.
  53. """
  54. from reflex.utils.serializers import serialize
  55. return self.__config__.json_dumps( # type: ignore
  56. self.dict(),
  57. default=serialize,
  58. )
  59. def set(self, **kwargs):
  60. """Set multiple fields and return the object.
  61. Args:
  62. **kwargs: The fields and values to set.
  63. Returns:
  64. The object with the fields set.
  65. """
  66. for key, value in kwargs.items():
  67. setattr(self, key, value)
  68. return self
  69. @classmethod
  70. def get_fields(cls) -> dict[str, Any]:
  71. """Get the fields of the object.
  72. Returns:
  73. The fields of the object.
  74. """
  75. return cls.__fields__
  76. @classmethod
  77. def add_field(cls, var: Any, default_value: Any):
  78. """Add a pydantic field after class definition.
  79. Used by State.add_var() to correctly handle the new variable.
  80. Args:
  81. var: The variable to add a pydantic field for.
  82. default_value: The default value of the field
  83. """
  84. new_field = ModelField.infer(
  85. name=var._var_name,
  86. value=default_value,
  87. annotation=var._var_type,
  88. class_validators=None,
  89. config=cls.__config__, # type: ignore
  90. )
  91. cls.__fields__.update({var._var_name: new_field})
  92. def get_value(self, key: str) -> Any:
  93. """Get the value of a field.
  94. Args:
  95. key: The key of the field.
  96. Returns:
  97. The value of the field.
  98. """
  99. if isinstance(key, str) and key in self.__fields__:
  100. # Seems like this function signature was wrong all along?
  101. # If the user wants a field that we know of, get it and pass it off to _get_value
  102. key = getattr(self, key)
  103. return self._get_value(
  104. key,
  105. to_dict=True,
  106. by_alias=False,
  107. include=None,
  108. exclude=None,
  109. exclude_unset=False,
  110. exclude_defaults=False,
  111. exclude_none=False,
  112. )