1
0

base.py 3.8 KB

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