base.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Define the base Pynecone class."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, TypeVar
  4. import pydantic
  5. # Typevar to represent any class subclassing Base.
  6. PcType = TypeVar("PcType")
  7. class Base(pydantic.BaseModel):
  8. """The base class subclassed by all Pynecone classes.
  9. This class wraps Pydantic and provides common methods such as
  10. serialization and setting fields.
  11. Any data structure that needs to be transferred between the
  12. frontend and backend should subclass this class.
  13. """
  14. class Config:
  15. """Pydantic config."""
  16. arbitrary_types_allowed = True
  17. use_enum_values = True
  18. def json(self) -> str:
  19. """Convert the object to a json string.
  20. Returns:
  21. The object as a json string.
  22. """
  23. return self.__config__.json_dumps(self.dict())
  24. def set(self: PcType, **kwargs) -> PcType:
  25. """Set multiple fields and return the object.
  26. Args:
  27. **kwargs: The fields and values to set.
  28. Returns:
  29. The object with the fields set.
  30. """
  31. for key, value in kwargs.items():
  32. setattr(self, key, value)
  33. return self
  34. @classmethod
  35. def get_fields(cls) -> Dict[str, Any]:
  36. """Get the fields of the object.
  37. Returns:
  38. The fields of the object.
  39. """
  40. return cls.__fields__
  41. def get_value(self, key: str) -> Any:
  42. """Get the value of a field.
  43. Args:
  44. key: The key of the field.
  45. Returns:
  46. The value of the field.
  47. """
  48. return self._get_value(
  49. key,
  50. to_dict=True,
  51. by_alias=False,
  52. include=None,
  53. exclude=None,
  54. exclude_unset=False,
  55. exclude_defaults=False,
  56. exclude_none=False,
  57. )