
    ]f9                    z   U d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
mZmZ ddlmZmZ ddlmZ ddlmZmZmZ d	d
lmZ d	dlmZmZ d	dlmZ  ej        d>i ej        ddi G d d                      Z ej        d>i ej        ddi G d d                      Zer_ee eeef         e!eef         ee         f         Z"de#d<   eej$        e"f         Z%eej&        e"f         Z' e
de%          Z( e
de'          Z)eddddd?d%            Z*eddddd@d(            Z*edddddAd+            Z*d,ed-dd.dBd1Z* e
d2e	def                   Z+edCd4            Z,edd-dd5dDd7            Z,	 dEd,d-ed5dFd:Z, e
d;          Z-eree-df         Z.dS  ej        d>i ej         G d< d=                      Z.dS )GzEThis module contains related classes and functions for serialization.    )annotationsN)partialmethod)TYPE_CHECKINGAnyCallableTypeVarUnionoverload)PydanticUndefinedcore_schema)r   )	AnnotatedLiteral	TypeAlias   )PydanticUndefinedAnnotation)_decorators_internal_dataclass)GetCoreSchemaHandlerfrozenTc                  B    e Zd ZU dZded<   eZded<   dZded<   ddZdS )PlainSerializeraC  Plain serializers use a function to modify the output of serialization.

    This is particularly helpful when you want to customize the serialization for annotated types.
    Consider an input of `list`, which will be serialized into a space-delimited string.

    ```python
    from typing import List

    from typing_extensions import Annotated

    from pydantic import BaseModel, PlainSerializer

    CustomStr = Annotated[
        List, PlainSerializer(lambda x: ' '.join(x), return_type=str)
    ]

    class StudentModel(BaseModel):
        courses: CustomStr

    student = StudentModel(courses=['Math', 'Chemistry', 'English'])
    print(student.model_dump())
    #> {'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'.
    zcore_schema.SerializerFunctionfuncr   return_typealways<Literal['always', 'unless-none', 'json', 'json-unless-none']	when_usedsource_typehandlerr   returncore_schema.CoreSchemac                    ||          }	 t          j        | j        | j        |                                          }n'# t
          $ r}t          j        |          |d}~ww xY w|t          u rdn|	                    |          }t          j        | j        t          j        | j        d          || j                  |d<   |S )zGets the Pydantic core schema.

        Args:
            source_type: The source type.
            handler: The `GetCoreSchemaHandler` instance.

        Returns:
            The Pydantic core schema.
        Nplainfunctioninfo_argreturn_schemar   serialization)r   get_function_return_typer   r   _get_types_namespace	NameErrorr   from_name_errorr   generate_schemar   $plain_serializer_function_ser_schemainspect_annotated_serializerr   selfr   r   schemar   er&   s          Q/var/www/html/env/lib/python3.11/site-packages/pydantic/functional_serializers.py__get_pydantic_core_schema__z,PlainSerializer.__get_pydantic_core_schema__7   s     %%	H%>	4+W-I-I-K-K KK  	H 	H 	H-=a@@aG	H +/@ @ @gF]F]^iFjFj"-"RY =diQQ'n	#
 #
 #
    2A   
A$
AA$Nr   r   r   r   r   r    	__name__
__module____qualname____doc____annotations__r   r   r   r4        r3   r   r      sd          > )((((K((((NVIVVVV     r>   r   c                  B    e Zd ZU dZded<   eZded<   dZded<   ddZdS )WrapSerializera	  Wrap 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 Any, Dict

    from typing_extensions import Annotated

    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 `helper` 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.WrapSerializerFunctionr   r   r   r   r   r   r   r   r   r   r    c                    ||          }	 t          j        | j        | j        |                                          }n'# t
          $ r}t          j        |          |d}~ww xY w|t          u rdn|	                    |          }t          j        | j        t          j        | j        d          || j                  |d<   |S )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.
        Nwrapr#   r'   )r   r(   r   r   r)   r*   r   r+   r   r,   r   #wrap_serializer_function_ser_schemar.   r   r/   s          r3   r4   z+WrapSerializer.__get_pydantic_core_schema__   s     %%	H%>	4+W-I-I-K-K KK  	H 	H 	H-=a@@aG	H +/@ @ @gF]F]^iFjFj"-"QY =diPP'n	#
 #
 #
 r5   Nr6   r7   r=   r>   r3   r@   r@   R   se         = =~ -,,,(K((((NVIVVVV     r>   r@   r   _PartialClsOrStaticMethod_PlainSerializeMethodType)bound_WrapSerializeMethodType.)r   r   check_fieldsfieldstrfieldsr   r   r   r   rH   bool | Noner   @Callable[[_PlainSerializeMethodType], _PlainSerializeMethodType]c                  d S Nr=   )rI   r   r   rH   rK   s        r3   field_serializerrP      s     HKsr>   modeLiteral['plain']c                  d S rO   r=   rI   rQ   r   r   rH   rK   s         r3   rP   rP      s     HKsr>   Literal['wrap']>Callable[[_WrapSerializeMethodType], _WrapSerializeMethodType]c                  d S rO   r=   rT   s         r3   rP   rP      s     FISr>   r"   r   )rQ   r   r   rH   Literal['plain', 'wrap']Callable[[Any], Any]c                $     d fd}|S )a  Decorator 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 typing import Set

    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(courses: Set[str]):
            return sorted(courses)

    student = StudentModel(courses={'Math', 'Chemistry', 'English'})
    print(student.model_dump_json())
    #> {"name":"Jane","courses":["Chemistry","English","Math"]}
    ```

    See [Custom serializers](../concepts/serialization.md#custom-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.
    fHCallable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any]r   (_decorators.PydanticDescriptorProxy[Any]c                `    t          j                  }t          j        | |          S )N)rK   rQ   r   r   rH   )r   FieldSerializerDecoratorInfoPydanticDescriptorProxy)r[   dec_inforH   rK   rQ   r   r   s     r3   deczfield_serializer.<locals>.dec  s@     ;#%
 
 
 21h???r>   )r[   r\   r   r]   r=   )rQ   r   r   rH   rK   rb   s   ````` r3   rP   rP      sK    j
@ 
@ 
@ 
@ 
@ 
@ 
@ 
@ 
@ 
@ Jr>   FuncType__fc                    d S rO   r=   )rd   s    r3   model_serializerrf   $  s    14r>   rQ   r   r   Callable[[FuncType], FuncType]c                    d S rO   r=   rg   s      r3   rf   rf   (  s	     &)Sr>   r[   Callable[..., Any] | Nonec              6    dfd}| |S  ||           S )a  Decorator that enables custom model serialization.

    This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields.

    An example would be to serialize temperature to the same temperature scale, such as degrees Celsius.

    ```python
    from typing import Literal

    from pydantic import BaseModel, model_serializer

    class TemperatureModel(BaseModel):
        unit: Literal['C', 'F']
        value: int

        @model_serializer()
        def serialize_model(self):
            if self.unit == 'F':
                return {'unit': 'C', 'value': int((self.value - 32) / 1.8)}
            return {'unit': self.unit, 'value': self.value}

    temperature = TemperatureModel(unit='F', value=212)
    print(temperature.model_dump())
    #> {'unit': 'C', 'value': 100}
    ```

    See [Custom serializers](../concepts/serialization.md#custom-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.
    r[   Callable[..., Any]r   r]   c                \    t          j                  }t          j        | |          S )N)rQ   r   r   )r   ModelSerializerDecoratorInfor`   )r[   ra   rQ   r   r   s     r3   rb   zmodel_serializer.<locals>.decc  s/    ;S^jsttt21h???r>   N)r[   rl   r   r]   r=   )r[   rQ   r   r   rb   s    ``` r3   rf   rf   1  sO    d@ @ @ @ @ @ @ @ 	y
s1vvr>   AnyTypec                  ,    e Zd ZddZdd	Zej        Zd
S )SerializeAsAnyitemr   r   c                8    t           |t                      f         S rO   )r   rq   )clsrr   s     r3   __class_getitem__z SerializeAsAny.__class_getitem__{  s    T>#3#3344r>   r   r   r   r    c                     ||          }|}|d         dk    r(|                                 }|d         }|d         dk    (t          j        d t          j                              |d<   |S )Ntypedefinitionsr1   c                     ||           S rO   r=   )xhs     r3   <lambda>z=SerializeAsAny.__get_pydantic_core_schema__.<locals>.<lambda>  s    QQqTT r>   )r1   r'   )copyr   rC   
any_schema)r0   r   r   r1   schema_to_updates        r3   r4   z+SerializeAsAny.__get_pydantic_core_schema__~  s     W[))F%"6*m;;#3#8#8#:#: #3H#=  #6*m;; 1<0_!!+*@*B*B1 1 1_- Mr>   N)rr   r   r   r   r6   )r8   r9   r:   ru   r4   object__hash__r=   r>   r3   rq   rq   y  s?        	5 	5 	5 	5	 	 	 	 ?r>   rq   r=   )rI   rJ   rK   rJ   r   r   r   r   rH   rL   r   rM   )rI   rJ   rK   rJ   rQ   rR   r   r   r   r   rH   rL   r   rM   )rI   rJ   rK   rJ   rQ   rU   r   r   r   r   rH   rL   r   rV   )rK   rJ   rQ   rX   r   r   r   r   rH   rL   r   rY   )rd   rc   r   rc   )rQ   rX   r   r   r   r   r   rh   rO   )
r[   rj   rQ   rX   r   r   r   r   r   rY   )/r;   
__future__r   dataclasses	functoolsr   typingr   r   r   r   r	   r
   pydantic_corer   r   _core_schematyping_extensionsr   r   r    r   	_internalr   r   annotated_handlersr   	dataclass
slots_truer   r@   classmethodstaticmethodrD   r<   SerializerFunction_PlainSerializationFunctionWrapSerializerFunction_WrapSerializationFunctionrE   rG   rP   rc   rf   ro   rq   r=   r>   r3   <module>r      sV   K K K " " " " " "     # # # # # # I I I I I I I I I I I I I I I I 8 8 8 8 8 8 8 8 5 5 5 5 5 5 ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) 7 7 7 7 7 7 7 7 4 4 4 4 4 4 EE,7EEEEE< < < < < < < FE<~ EE,7EEEEE\ \ \ \ \ \ \ FE\~  e+0S#s]1K\Z]_bZbMcersvew1w+xxxxx"'(GIb(b"c!&|'JLe'e!f '(CKf g g g&w'AIcddd 

 NQ #K K K K K 
K 
 NQ #K K K K K 
K 
 NQ #I I I I I 
I &-(NV $A A A A A AH 7:Xc3h%7888 
 4 4 4 
 4 
 &)NV	) ) ) ) ) 
) $(9 &-NV(9 9 9 9 9 9x ')

  #w|,N  [<<0;<<# # # # # # # =<# # #r>   