base.py 4.1 KB

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