fL iB@UdZddlmZddlZddlmZmZddlmZm Z m Z m Z m Z m Z mZddlmZmZddlmZmZmZddlmZd d lmZd d lmZmZd d lmZej>ddd#Z*d$ed%dd" d?d&Z*erme e ee ge fZ+de$d'< e e ge fZ,de$d(< d)Z-de$d*< e e eee ge fZ.de$d+< e e ege fZ/de$d,< d-Z0de$d.< d/Z1de$d0<e d1e-Z2e d2e0Z3ed@d3Z4ed%dd4 dAd5Z4edd%dd6 dBd7Z4 dCd$d%ed6 dDd8Z4e d9Z5ere e5dfZ6yej>d {'courses': 'Math Chemistry English'} ``` Attributes: func: The serializer function. return_type: The return type for the function. If omitted it will be inferred from the type annotation. when_used: Determines when this serializer should be used. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. zcore_schema.SerializerFunctionfuncr return_typealwaysr when_usedc||}|jtur |j}n: tj|j|j j }|turdn|j|}tj|jtj|jd||j|d<|S#t$r}tj||d}~wwxYw)zGets the Pydantic core schema. Args: source_type: The source type. handler: The `GetCoreSchemaHandler` instance. Returns: The Pydantic core schema. localnsNplainfunctioninfo_arg return_schemar serialization)rr rget_callable_return_typer_get_types_namespacelocals NameErrorrfrom_name_errorgenerate_schemar$plain_serializer_function_ser_schemainspect_annotated_serializerrself source_typehandlerschemarer&s e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pydantic/functional_serializers.py__get_pydantic_core_schema__z,PlainSerializer.__get_pydantic_core_schema__5s%   #4 4**K L*BBII#88:AA !,/@ @gF]F]^iFj "-"R"RYY ==diiQ'nn #    L1AA!D!K L9C C1C,,C1Nr2rr3rreturnzcore_schema.CoreSchema __name__ __module__ __qualname____doc____annotations__r rrr7r6rrs(: )((K("Ix" rBrc@eZdZUdZded<eZded<dZded<d d Zy ) WrapSerializeraWrap serializers receive the raw inputs along with a handler function that applies the standard serialization logic, and can modify the resulting value before returning it as the final output of serialization. For example, here's a scenario in which a wrap serializer transforms timezones to UTC **and** utilizes the existing `datetime` serialization logic. ```python from datetime import datetime, timezone from typing import Annotated, Any from pydantic import BaseModel, WrapSerializer class EventDatetime(BaseModel): start: datetime end: datetime def convert_to_utc(value: Any, handler, info) -> dict[str, datetime]: # Note that `handler` can actually help serialize the `value` for # further custom serialization in case it's a subclass. partial_result = handler(value, info) if info.mode == 'json': return { k: datetime.fromisoformat(v).astimezone(timezone.utc) for k, v in partial_result.items() } return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()} UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)] class EventModel(BaseModel): event_datetime: UTCEventDatetime dt = EventDatetime( start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00' ) event = EventModel(event_datetime=dt) print(event.model_dump()) ''' { 'event_datetime': { 'start': datetime.datetime( 2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc ), 'end': datetime.datetime( 2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc ), } } ''' print(event.model_dump_json()) ''' {"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}} ''' ``` Attributes: func: The serializer function to be wrapped. return_type: The return type for the function. If omitted it will be inferred from the type annotation. when_used: Determines when this serializer should be used. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. z"core_schema.WrapSerializerFunctionrrrrrrc||}|jtur |j}n: tj|j|j j }|turdn|j|}tj|jtj|jd||j|d<|S#t$r}tj||d}~wwxYw)zThis method is used to get the Pydantic core schema of the class. Args: source_type: Source type. handler: Core schema handler. Returns: The generated core schema of the class. r Nwrapr#r')rr rr(rr)r*r+rr,r-r#wrap_serializer_function_ser_schemar/rr0s r6r7z+WrapSerializer.__get_pydantic_core_schema__s%   #4 4**K L*BBII#88:AA !,/@ @gF]F]^iFj "-"Q"QYY ==diiP'nn #    L1AA!D!K Lr8Nr9r;rArBr6rDrDXs)<| -,(K("Ix" rBrDz!partial[Any] | partialmethod[Any]r_Partialz)core_schema.SerializerFunction | _PartialFieldPlainSerializerz-core_schema.WrapSerializerFunction | _PartialFieldWrapSerializerz*FieldPlainSerializer | FieldWrapSerializerFieldSerializer_FieldPlainSerializerT)bound_FieldWrapSerializerT.)rr check_fieldscyNrAfieldmoderrrOfieldss r6field_serializerrVs @CrB)rTrrrOcyrQrArRs r6rVrVs BErBr"rc$dfd }|S)aDecorator that enables custom field serialization. In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list. ```python from pydantic import BaseModel, field_serializer class StudentModel(BaseModel): name: str = 'Jane' courses: set[str] @field_serializer('courses', when_used='json') def serialize_courses_in_order(self, courses: set[str]): return sorted(courses) student = StudentModel(courses={'Math', 'Chemistry', 'English'}) print(student.model_dump_json()) #> {"name":"Jane","courses":["Chemistry","English","Math"]} ``` See [the usage documentation](../concepts/serialization.md#serializers) for more information. Four signatures are supported: - `(self, value: Any, info: FieldSerializationInfo)` - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)` - `(value: Any, info: SerializationInfo)` - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` Args: fields: Which field(s) the method should be called on. mode: The serialization mode. - `plain` means the function will be called instead of the default serialization logic, - `wrap` means the function will be called with an argument to optionally call the default serialization logic. return_type: Optional return type for the function, if omitted it will be inferred from the type annotation. when_used: Determines the serializer will be used for serialization. check_fields: Whether to check that the fields actually exist on the model. Returns: The decorator function. cdtj}tj||S)N)rUrTrrrO)rFieldSerializerDecoratorInfoPydanticDescriptorProxy)fdec_inforOrUrTrrs r6deczfield_serializer..decs7;;#%  221h??rB)r\rKr:(_decorators.PydanticDescriptorProxy[Any]rA)rTrrrOrUr^s````` r6rVrVsn@@ JrBModelPlainSerializerWithInfoModelPlainSerializerWithoutInfoz>ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfoModelPlainSerializerModelWrapSerializerWithInfoModelWrapSerializerWithoutInfoz {'unit': 'C', 'value': 100} ``` Two signatures are supported for `mode='plain'`, which is the default: - `(self)` - `(self, info: SerializationInfo)` And two other signatures for `mode='wrap'`: - `(self, nxt: SerializerFunctionWrapHandler)` - `(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` See [the usage documentation](../concepts/serialization.md#serializers) for more information. Args: f: The function to be decorated. mode: The serialization mode. - `'plain'` means the function will be called instead of the default serialization logic - `'wrap'` means the function will be called with an argument to optionally call the default serialization logic. when_used: Determines when this serializer should be used. return_type: The return type for the function. If omitted it will be inferred from the type annotation. Returns: The decorator function. c`tj}tj||S)N)rTrr)rModelSerializerDecoratorInfor[)r\r]rTrrs r6r^zmodel_serializer..decs,;;S^jst221h??rB)r\rfr:r_rA)r\rTrrr^s ``` r6rjrjYs@@ y 1v rBAnyTypecDeZdZdZddZ ddZejZy)SerializeAsAnyzAnnotation used to mark a type as having duck-typing serialization behavior. See [usage documentation](../concepts/serialization.md#serializing-with-duck-typing) for more details. c(t|tfSrQ)rrs)clsitems r6__class_getitem__z SerializeAsAny.__class_getitem__sT>#334 4rBc||}|}|ddk(r|j}|d}|ddk(rtjd|d<|S)Ntype definitionsr4anyr')copyrsimple_ser_schema)r1r2r3r4schema_to_updates r6r7z+SerializeAsAny.__get_pydantic_core_schema__sg[)F% "6*m;#3#8#8#: #3H#= #6*m;1<0M0Me0T _ -MrBN)rvrr:rr9)r<r=r>r?rwr7object__hash__rArBr6rsrss4  5 " -A  # ??rBrsrA)rSstrrUrrTLiteral['wrap']rrrrrO bool | Noner:z8Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT])rSrrUrrTLiteral['plain']rrrrrOrr:z:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]) rUrrTLiteral['plain', 'wrap']rrrrrOrr:zuCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT])r\rgr:rg)rTrrrrrr:z8Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT])rTrrrrrr:z:Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]rQ) r\z5_ModelPlainSerializerT | _ModelWrapSerializerT | NonerTrrrrrr:z_ModelPlainSerializerT | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT])7r? __future__r dataclasses functoolsrrtypingrrrr r r r pydantic_corer rpydantic_core.core_schemarrrtyping_extensionsrr _internalrrannotated_handlersr dataclass slots_truerrDrHr@rIrJrKrLrNrVr`rarbrcrdrerfrgrhrjrqrsrArBr6rs=K",VVV8``')74E,77EEBBFBJE,77EEccFcL=Hi=&Q)Q@%TT?!MOYM0$%=EYZ#$;CVW  #C CC  C  C  CC>C C ! #E EE  E  E  EE@E E&-(" $ A A "A A  A  AAAH/7=Ns=S7TVY7Y.Z )ZN193%*1E#YEQ&f)f4-5s