functional_serializers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """This module contains related classes and functions for serialization."""
  2. from __future__ import annotations
  3. import dataclasses
  4. from functools import partialmethod
  5. from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, overload
  6. from pydantic_core import PydanticUndefined, core_schema
  7. from pydantic_core import core_schema as _core_schema
  8. from typing_extensions import Annotated, Literal, TypeAlias
  9. from . import PydanticUndefinedAnnotation
  10. from ._internal import _decorators, _internal_dataclass
  11. from .annotated_handlers import GetCoreSchemaHandler
  12. @dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
  13. class PlainSerializer:
  14. """Plain serializers use a function to modify the output of serialization.
  15. Attributes:
  16. func: The serializer function.
  17. return_type: The return type for the function. If omitted it will be inferred from the type annotation.
  18. when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
  19. `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
  20. """
  21. func: core_schema.SerializerFunction
  22. return_type: Any = PydanticUndefined
  23. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always'
  24. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  25. """Gets the Pydantic core schema.
  26. Args:
  27. source_type: The source type.
  28. handler: The `GetCoreSchemaHandler` instance.
  29. Returns:
  30. The Pydantic core schema.
  31. """
  32. schema = handler(source_type)
  33. try:
  34. return_type = _decorators.get_function_return_type(
  35. self.func, self.return_type, handler._get_types_namespace()
  36. )
  37. except NameError as e:
  38. raise PydanticUndefinedAnnotation.from_name_error(e) from e
  39. return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type)
  40. schema['serialization'] = core_schema.plain_serializer_function_ser_schema(
  41. function=self.func,
  42. info_arg=_decorators.inspect_annotated_serializer(self.func, 'plain'),
  43. return_schema=return_schema,
  44. when_used=self.when_used,
  45. )
  46. return schema
  47. @dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
  48. class WrapSerializer:
  49. """Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization
  50. logic, and can modify the resulting value before returning it as the final output of serialization.
  51. Attributes:
  52. func: The serializer function to be wrapped.
  53. return_type: The return type for the function. If omitted it will be inferred from the type annotation.
  54. when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
  55. `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
  56. """
  57. func: core_schema.WrapSerializerFunction
  58. return_type: Any = PydanticUndefined
  59. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always'
  60. def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
  61. """This method is used to get the Pydantic core schema of the class.
  62. Args:
  63. source_type: Source type.
  64. handler: Core schema handler.
  65. Returns:
  66. The generated core schema of the class.
  67. """
  68. schema = handler(source_type)
  69. try:
  70. return_type = _decorators.get_function_return_type(
  71. self.func, self.return_type, handler._get_types_namespace()
  72. )
  73. except NameError as e:
  74. raise PydanticUndefinedAnnotation.from_name_error(e) from e
  75. return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type)
  76. schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
  77. function=self.func,
  78. info_arg=_decorators.inspect_annotated_serializer(self.func, 'wrap'),
  79. return_schema=return_schema,
  80. when_used=self.when_used,
  81. )
  82. return schema
  83. if TYPE_CHECKING:
  84. _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
  85. _PlainSerializationFunction = Union[_core_schema.SerializerFunction, _PartialClsOrStaticMethod]
  86. _WrapSerializationFunction = Union[_core_schema.WrapSerializerFunction, _PartialClsOrStaticMethod]
  87. _PlainSerializeMethodType = TypeVar('_PlainSerializeMethodType', bound=_PlainSerializationFunction)
  88. _WrapSerializeMethodType = TypeVar('_WrapSerializeMethodType', bound=_WrapSerializationFunction)
  89. @overload
  90. def field_serializer(
  91. __field: str,
  92. *fields: str,
  93. return_type: Any = ...,
  94. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = ...,
  95. check_fields: bool | None = ...,
  96. ) -> Callable[[_PlainSerializeMethodType], _PlainSerializeMethodType]:
  97. ...
  98. @overload
  99. def field_serializer(
  100. __field: str,
  101. *fields: str,
  102. mode: Literal['plain'],
  103. return_type: Any = ...,
  104. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = ...,
  105. check_fields: bool | None = ...,
  106. ) -> Callable[[_PlainSerializeMethodType], _PlainSerializeMethodType]:
  107. ...
  108. @overload
  109. def field_serializer(
  110. __field: str,
  111. *fields: str,
  112. mode: Literal['wrap'],
  113. return_type: Any = ...,
  114. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = ...,
  115. check_fields: bool | None = ...,
  116. ) -> Callable[[_WrapSerializeMethodType], _WrapSerializeMethodType]:
  117. ...
  118. def field_serializer(
  119. *fields: str,
  120. mode: Literal['plain', 'wrap'] = 'plain',
  121. return_type: Any = PydanticUndefined,
  122. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
  123. check_fields: bool | None = None,
  124. ) -> Callable[[Any], Any]:
  125. """Decorator that enables custom field serialization.
  126. See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information.
  127. Four signatures are supported:
  128. - `(self, value: Any, info: FieldSerializationInfo)`
  129. - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)`
  130. - `(value: Any, info: SerializationInfo)`
  131. - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`
  132. Args:
  133. fields: Which field(s) the method should be called on.
  134. mode: The serialization mode.
  135. - `plain` means the function will be called instead of the default serialization logic,
  136. - `wrap` means the function will be called with an argument to optionally call the
  137. default serialization logic.
  138. return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
  139. when_used: Determines the serializer will be used for serialization.
  140. check_fields: Whether to check that the fields actually exist on the model.
  141. Returns:
  142. The decorator function.
  143. """
  144. def dec(
  145. f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any]
  146. ) -> _decorators.PydanticDescriptorProxy[Any]:
  147. dec_info = _decorators.FieldSerializerDecoratorInfo(
  148. fields=fields,
  149. mode=mode,
  150. return_type=return_type,
  151. when_used=when_used,
  152. check_fields=check_fields,
  153. )
  154. return _decorators.PydanticDescriptorProxy(f, dec_info)
  155. return dec
  156. FuncType = TypeVar('FuncType', bound=Callable[..., Any])
  157. @overload
  158. def model_serializer(__f: FuncType) -> FuncType:
  159. ...
  160. @overload
  161. def model_serializer(
  162. *,
  163. mode: Literal['plain', 'wrap'] = ...,
  164. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
  165. return_type: Any = ...,
  166. ) -> Callable[[FuncType], FuncType]:
  167. ...
  168. def model_serializer(
  169. __f: Callable[..., Any] | None = None,
  170. *,
  171. mode: Literal['plain', 'wrap'] = 'plain',
  172. when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
  173. return_type: Any = PydanticUndefined,
  174. ) -> Callable[[Any], Any]:
  175. """Decorator that enables custom model serialization.
  176. See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information.
  177. Args:
  178. __f: The function to be decorated.
  179. mode: The serialization mode.
  180. - `'plain'` means the function will be called instead of the default serialization logic
  181. - `'wrap'` means the function will be called with an argument to optionally call the default
  182. serialization logic.
  183. when_used: Determines when this serializer should be used.
  184. return_type: The return type for the function. If omitted it will be inferred from the type annotation.
  185. Returns:
  186. The decorator function.
  187. """
  188. def dec(f: Callable[..., Any]) -> _decorators.PydanticDescriptorProxy[Any]:
  189. dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used)
  190. return _decorators.PydanticDescriptorProxy(f, dec_info)
  191. if __f is None:
  192. return dec
  193. else:
  194. return dec(__f) # type: ignore
  195. AnyType = TypeVar('AnyType')
  196. if TYPE_CHECKING:
  197. SerializeAsAny = Annotated[AnyType, ...] # SerializeAsAny[list[str]] will be treated by type checkers as list[str]
  198. """Force serialization to ignore whatever is defined in the schema and instead ask the object
  199. itself how it should be serialized.
  200. In particular, this means that when model subclasses are serialized, fields present in the subclass
  201. but not in the original schema will be included.
  202. """
  203. else:
  204. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  205. class SerializeAsAny: # noqa: D101
  206. def __class_getitem__(cls, item: Any) -> Any:
  207. return Annotated[item, SerializeAsAny()]
  208. def __get_pydantic_core_schema__(
  209. self, source_type: Any, handler: GetCoreSchemaHandler
  210. ) -> core_schema.CoreSchema:
  211. schema = handler(source_type)
  212. schema_to_update = schema
  213. while schema_to_update['type'] == 'definitions':
  214. schema_to_update = schema_to_update.copy()
  215. schema_to_update = schema_to_update['schema']
  216. schema_to_update['serialization'] = core_schema.wrap_serializer_function_ser_schema(
  217. lambda x, h: h(x), schema=core_schema.any_schema()
  218. )
  219. return schema
  220. __hash__ = object.__hash__