base.py 3.8 KB

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