base.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. """Define the base Reflex class."""
  2. from __future__ import annotations
  3. import os
  4. from typing import TYPE_CHECKING, Any
  5. import pydantic.v1.main as pydantic_main
  6. from pydantic.v1 import BaseModel
  7. from pydantic.v1.fields import ModelField
  8. def validate_field_name(bases: list[type[BaseModel]], field_name: str) -> None:
  9. """Ensure that the field's name does not shadow an existing attribute of the model.
  10. Args:
  11. bases: List of base models to check for shadowed attrs.
  12. field_name: name of attribute
  13. Raises:
  14. VarNameError: If state var field shadows another in its parent state
  15. """
  16. from reflex.utils.exceptions import VarNameError
  17. # can't use reflex.config.environment here cause of circular import
  18. reload = os.getenv("__RELOAD_CONFIG", "").lower() == "true"
  19. base = None
  20. try:
  21. for base in bases:
  22. if not reload and getattr(base, field_name, None):
  23. pass
  24. except TypeError as te:
  25. msg = (
  26. f'State var "{field_name}" in {base} has been shadowed by a substate var; '
  27. f'use a different field name instead".'
  28. )
  29. raise VarNameError(msg) from te
  30. # monkeypatch pydantic validate_field_name method to skip validating
  31. # shadowed state vars when reloading app via utils.prerequisites.get_app(reload=True)
  32. pydantic_main.validate_field_name = validate_field_name # pyright: ignore [reportPrivateImportUsage]
  33. if TYPE_CHECKING:
  34. from reflex.vars import Var
  35. class Base(BaseModel):
  36. """The base class subclassed by all Reflex classes.
  37. This class wraps Pydantic and provides common methods such as
  38. serialization and setting fields.
  39. Any data structure that needs to be transferred between the
  40. frontend and backend should subclass this class.
  41. """
  42. class Config:
  43. """Pydantic config."""
  44. arbitrary_types_allowed = True
  45. use_enum_values = True
  46. extra = "allow"
  47. def json(self) -> str:
  48. """Convert the object to a json string.
  49. Returns:
  50. The object as a json string.
  51. """
  52. from reflex.utils.serializers import serialize
  53. return self.__config__.json_dumps(
  54. self.dict(),
  55. default=serialize,
  56. )
  57. def set(self, **kwargs: Any):
  58. """Set multiple fields and return the object.
  59. Args:
  60. **kwargs: The fields and values to set.
  61. Returns:
  62. The object with the fields set.
  63. """
  64. for key, value in kwargs.items():
  65. setattr(self, key, value)
  66. return self
  67. @classmethod
  68. def get_fields(cls) -> dict[str, ModelField]:
  69. """Get the fields of the object.
  70. Returns:
  71. The fields of the object.
  72. """
  73. return cls.__fields__
  74. @classmethod
  75. def add_field(cls, var: Var, default_value: Any):
  76. """Add a pydantic field after class definition.
  77. Used by State.add_var() to correctly handle the new variable.
  78. Args:
  79. var: The variable to add a pydantic field for.
  80. default_value: The default value of the field
  81. """
  82. var_name = var._var_field_name
  83. new_field = ModelField.infer(
  84. name=var_name,
  85. value=default_value,
  86. annotation=var._var_type,
  87. class_validators=None,
  88. config=cls.__config__,
  89. )
  90. cls.__fields__.update({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):
  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. return getattr(self, key)
  102. return key