base.py 3.5 KB

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