base.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Define the base Pynecone class."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, TypeVar
  4. import pydantic
  5. from pydantic.fields import ModelField
  6. # Typevar to represent any class subclassing Base.
  7. PcType = TypeVar("PcType")
  8. class Base(pydantic.BaseModel):
  9. """The base class subclassed by all Pynecone classes.
  10. This class wraps Pydantic and provides common methods such as
  11. serialization and setting fields.
  12. Any data structure that needs to be transferred between the
  13. frontend and backend should subclass this class.
  14. """
  15. class Config:
  16. """Pydantic config."""
  17. arbitrary_types_allowed = True
  18. use_enum_values = True
  19. def json(self) -> str:
  20. """Convert the object to a json string.
  21. Returns:
  22. The object as a json string.
  23. """
  24. return self.__config__.json_dumps(self.dict())
  25. def set(self: PcType, **kwargs) -> PcType:
  26. """Set multiple fields and return the object.
  27. Args:
  28. **kwargs: The fields and values to set.
  29. Returns:
  30. The object with the fields set.
  31. """
  32. for key, value in kwargs.items():
  33. setattr(self, key, value)
  34. return self
  35. @classmethod
  36. def get_fields(cls) -> Dict[str, Any]:
  37. """Get the fields of the object.
  38. Returns:
  39. The fields of the object.
  40. """
  41. return cls.__fields__
  42. @classmethod
  43. def add_field(cls, var: Any, default_value: Any):
  44. """Add a pydantic field after class definition.
  45. Used by State.add_var() to correctly handle the new variable.
  46. Args:
  47. var: The variable to add a pydantic field for.
  48. default_value: The default value of the field
  49. """
  50. new_field = ModelField.infer(
  51. name=var.name,
  52. value=default_value,
  53. annotation=var.type_,
  54. class_validators=None,
  55. config=cls.__config__,
  56. )
  57. cls.__fields__.update({var.name: new_field})
  58. def get_value(self, key: str) -> Any:
  59. """Get the value of a field.
  60. Args:
  61. key: The key of the field.
  62. Returns:
  63. The value of the field.
  64. """
  65. return self._get_value(
  66. key,
  67. to_dict=True,
  68. by_alias=False,
  69. include=None,
  70. exclude=None,
  71. exclude_unset=False,
  72. exclude_defaults=False,
  73. exclude_none=False,
  74. )