|
1 |
| -import json |
2 |
| -from typing import Any |
| 1 | +"""A data converter for Pydantic v2. |
3 | 2 |
|
4 |
| -from temporalio.api.common.v1 import Payload |
| 3 | +To use, pass ``pydantic_data_converter`` as the ``data_converter`` argument to |
| 4 | +:py:class:`temporalio.client.Client`: |
| 5 | +
|
| 6 | +.. code-block:: python |
| 7 | +
|
| 8 | + client = Client( |
| 9 | + data_converter=pydantic_data_converter, |
| 10 | + ... |
| 11 | + ) |
| 12 | +
|
| 13 | +Pydantic v1 is not supported. |
| 14 | +""" |
| 15 | + |
| 16 | +from typing import Any, Optional, Type |
| 17 | + |
| 18 | +import temporalio.api.common.v1 |
| 19 | +from pydantic import TypeAdapter |
| 20 | +from pydantic_core import to_json |
5 | 21 | from temporalio.converter import (
|
6 | 22 | CompositePayloadConverter,
|
7 | 23 | DataConverter,
|
8 | 24 | DefaultPayloadConverter,
|
| 25 | + EncodingPayloadConverter, |
9 | 26 | JSONPlainPayloadConverter,
|
10 | 27 | )
|
11 | 28 |
|
12 |
| -try: # noqa: SIM105 |
13 |
| - from pydantic.json import pydantic_encoder |
14 |
| -except ImportError: |
15 |
| - pass |
| 29 | +# Note that in addition to the implementation in this module, _RestrictedProxy |
| 30 | +# implements __get_pydantic_core_schema__ so that pydantic unwraps proxied types. |
16 | 31 |
|
17 | 32 |
|
18 |
| -class PydanticJSONPayloadConverter(JSONPlainPayloadConverter): |
| 33 | +class PydanticJSONPlainPayloadConverter(EncodingPayloadConverter): |
19 | 34 | """Pydantic JSON payload converter.
|
20 | 35 |
|
21 |
| - This extends the :py:class:`JSONPlainPayloadConverter` to override |
22 |
| - :py:meth:`to_payload` using the Pydantic encoder. |
| 36 | + Supports conversion of all types supported by Pydantic to and from JSON. |
| 37 | +
|
| 38 | + In addition to Pydantic models, these include all `json.dump`-able types, |
| 39 | + various non-`json.dump`-able standard library types such as dataclasses, |
| 40 | + types from the datetime module, sets, UUID, etc, and custom types composed |
| 41 | + of any of these. |
| 42 | +
|
| 43 | + See https://docs.pydantic.dev/latest/api/standard_library_types/ |
23 | 44 | """
|
24 | 45 |
|
25 |
| - def to_payload(self, value: Any) -> Payload | None: |
26 |
| - """Convert all values with Pydantic encoder or fail. |
| 46 | + @property |
| 47 | + def encoding(self) -> str: |
| 48 | + """See base class.""" |
| 49 | + return "json/plain" |
| 50 | + |
| 51 | + def to_payload(self, value: Any) -> Optional[temporalio.api.common.v1.Payload]: |
| 52 | + """See base class. |
| 53 | +
|
| 54 | + Uses ``pydantic_core.to_json`` to serialize ``value`` to JSON. |
27 | 55 |
|
28 |
| - Like the base class, we fail if we cannot convert. This payload |
29 |
| - converter is expected to be the last in the chain, so it can fail if |
30 |
| - unable to convert. |
| 56 | + See |
| 57 | + https://docs.pydantic.dev/latest/api/pydantic_core/#pydantic_core.to_json. |
31 | 58 | """
|
32 |
| - # We let JSON conversion errors be thrown to caller |
33 |
| - return Payload( |
34 |
| - metadata={"encoding": self.encoding.encode()}, |
35 |
| - data=json.dumps(value, separators=(",", ":"), sort_keys=True, default=pydantic_encoder).encode(), |
36 |
| - ) |
| 59 | + return temporalio.api.common.v1.Payload(metadata={"encoding": self.encoding.encode()}, data=to_json(value)) |
| 60 | + |
| 61 | + def from_payload( |
| 62 | + self, |
| 63 | + payload: temporalio.api.common.v1.Payload, |
| 64 | + type_hint: Optional[Type] = None, |
| 65 | + ) -> Any: |
| 66 | + """See base class. |
| 67 | +
|
| 68 | + Uses ``pydantic.TypeAdapter.validate_json`` to construct an |
| 69 | + instance of the type specified by ``type_hint`` from the JSON payload. |
| 70 | +
|
| 71 | + See |
| 72 | + https://docs.pydantic.dev/latest/api/type_adapter/#pydantic.type_adapter.TypeAdapter.validate_json. |
| 73 | + """ |
| 74 | + _type_hint = type_hint if type_hint is not None else Any |
| 75 | + return TypeAdapter(_type_hint).validate_json(payload.data) |
37 | 76 |
|
38 | 77 |
|
39 | 78 | class PydanticPayloadConverter(CompositePayloadConverter):
|
40 |
| - """Payload converter that replaces Temporal JSON conversion with Pydantic |
41 |
| - JSON conversion. |
| 79 | + """Payload converter for payloads containing pydantic model instances. |
| 80 | +
|
| 81 | + JSON conversion is replaced with a converter that uses |
| 82 | + :py:class:`PydanticJSONPlainPayloadConverter`. |
42 | 83 | """
|
43 | 84 |
|
44 | 85 | def __init__(self) -> None:
|
| 86 | + """Initialize object""" |
| 87 | + json_payload_converter = PydanticJSONPlainPayloadConverter() |
45 | 88 | super().__init__(
|
46 | 89 | *(
|
47 |
| - converter if not isinstance(converter, JSONPlainPayloadConverter) else PydanticJSONPayloadConverter() |
48 |
| - for converter in DefaultPayloadConverter.default_encoding_payload_converters |
49 |
| - ), |
| 90 | + c if not isinstance(c, JSONPlainPayloadConverter) else json_payload_converter |
| 91 | + for c in DefaultPayloadConverter.default_encoding_payload_converters |
| 92 | + ) |
50 | 93 | )
|
51 | 94 |
|
52 | 95 |
|
53 | 96 | pydantic_data_converter = DataConverter(payload_converter_class=PydanticPayloadConverter)
|
| 97 | +"""Pydantic data converter. |
| 98 | +
|
| 99 | +Supports conversion of all types supported by Pydantic to and from JSON. |
| 100 | +
|
| 101 | +In addition to Pydantic models, these include all `json.dump`-able types, |
| 102 | +various non-`json.dump`-able standard library types such as dataclasses, |
| 103 | +types from the datetime module, sets, UUID, etc, and custom types composed |
| 104 | +of any of these. |
| 105 | +
|
| 106 | +To use, pass as the ``data_converter`` argument of :py:class:`temporalio.client.Client` |
| 107 | +""" |
0 commit comments