o
    ¨Ýj	F  ã                   @  sÒ  U d Z ddlmZ ddlZddlmZ ddlmZmZ ddl	m
Z
mZmZmZmZmZmZ ddlmZmZ ddlmZmZmZ dd	lmZ d
dlmZ d
dlmZ d
dlmZ d
dl m!Z! ej"ddd�G dd„ dƒƒZ#ej"ddd�G dd„ dƒƒZ$e
r¢dZ%de&d< dZ'de&d< 	 dZ(de&d< 	 dZ)de&d< 	 ede'd�Z*ed e(d�Z+ed!d!d!d"œdWd0d1„ƒZ,ed!d!d!d!d2œdXd5d1„ƒZ,d6ed7dd2œdYd:d1„Z,e
�r!eeee gef Z-de&d;< 	 eegef Z.de&d<< 	 d=Z/de&d>< 	 eeeee gef Z0de&d?< 	 eeegef Z1de&d@< 	 dAZ2de&dB< 	 dCZ3de&dD< edEe/d�Z4edFe2d�Z5edZdHdI„ƒZ6ed7d!dJœd[dLdI„ƒZ6ed!d7d!dMœd\dOdI„ƒZ6	d]d6d7edMœd^dRdI„Z6edSƒZ7e
�rZee7d!f Z8dS ej"ddT�G dUdV„ dVƒƒZ8dS )_zEThis module contains related classes and functions for serialization.é    )ÚannotationsN)ÚCallable)ÚpartialÚpartialmethod)ÚTYPE_CHECKINGÚ	AnnotatedÚAnyÚLiteralÚ	TypeAliasÚTypeVarÚoverload)ÚPydanticUndefinedÚcore_schema)ÚSerializationInfoÚSerializerFunctionWrapHandlerÚWhenUsed)ÚTypeFormé   )ÚPydanticUndefinedAnnotation)Ú_decorators)ÚGetCoreSchemaHandler)ÚPydanticUserErrorT)ÚslotsÚfrozenc                   @  ó<   e Zd ZU dZded< eZded< dZded< ddd„ZdS )ÚPlainSerializera  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 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ÚfuncúTypeForm[Any]Úreturn_typeÚalwaysr   Ú	when_usedÚsource_typer   Úhandlerr   Úreturnúcore_schema.CoreSchemac              
   C  ó˜   ||ƒ}| j tur| j }n ztj| j| ¡ jd�}W n ty, } zt 	|¡|‚d}~ww |tu r3dn| 
|¡}tj| jt | jd¡|| jd�|d< |S )zÒGets the Pydantic core schema.

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

        Returns:
            The Pydantic core schema.
        ©ÚlocalnsNÚplain©ÚfunctionZinfo_argÚreturn_schemar    Úserialization)r   r   r   Úget_callable_return_typer   Ú_get_types_namespaceÚlocalsÚ	NameErrorr   Úfrom_name_errorÚgenerate_schemar   Z$plain_serializer_function_ser_schemaÚinspect_annotated_serializerr    ©Úselfr!   r"   Úschemar   Úer+   © r8   úZ/var/www/html/chatgpt/venv/lib/python3.10/site-packages/pydantic/functional_serializers.pyÚ__get_pydantic_core_schema__7   ó(   


þ€ÿ
üz,PlainSerializer.__get_pydantic_core_schema__N©r!   r   r"   r   r#   r$   ©	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r    r:   r8   r8   r8   r9   r      s   
 r   c                   @  r   )Ú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 Annotated, Any

    from pydantic import (
        BaseModel,
        SerializationInfo,
        SerializerFunctionWrapHandler,
        WrapSerializer,
    )

    def convert_to_utc(
        value: Any, handler: SerializerFunctionWrapHandler, info: SerializationInfo
    ):
        # Note that `handler` can actually help serialize the `value` for
        # further custom serialization in case it's a subclass.
        serialized = handler(value)
        if info.mode == 'json':
            return datetime.fromisoformat(serialized).astimezone(timezone.utc)
        else:
            return serialized.astimezone(timezone.utc)

    UTCDatetime = Annotated[datetime, WrapSerializer(convert_to_utc)]

    class EventModel(BaseModel):
        event_datetime: UTCDatetime

    event = EventModel(event_datetime='2024-01-01T07:00:00-08:00')
    print(event.model_dump())
    '''
    {
        'event_datetime': datetime.datetime(
            2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc
        )
    }
    '''

    print(event.model_dump_json())
    #> {"event_datetime":"2024-01-01T15: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#   r$   c              
   C  r%   )zïThis 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&   NÚwrapr)   r,   )r   r   r   r-   r   r.   r/   r0   r   r1   r2   r   Z#wrap_serializer_function_ser_schemar3   r    r4   r8   r8   r9   r:   •   r;   z+WrapSerializer.__get_pydantic_core_schema__Nr<   r=   r8   r8   r8   r9   rC   Z   s   
 5rC   z!partial[Any] | partialmethod[Any]r
   Ú_Partialz)core_schema.SerializerFunction | _PartialÚFieldPlainSerializerz-core_schema.WrapSerializerFunction | _PartialÚFieldWrapSerializerz*FieldPlainSerializer | FieldWrapSerializerÚFieldSerializerÚ_FieldPlainSerializerT)ÚboundÚ_FieldWrapSerializerT.)r   r    Úcheck_fieldsÚfieldÚstrÚfieldsÚmodeúLiteral['wrap']r   r   r    r   rL   úbool | Noner#   ú8Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]c               G  ó   d S ©Nr8   ©rM   rP   r   r    rL   rO   r8   r8   r9   Úfield_serializerÈ   ó   	rW   )rP   r   r    rL   úLiteral['plain']ú:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c               G  rT   rU   r8   rV   r8   r8   r9   rW   Ô   rX   r(   r   úLiteral['plain', 'wrap']úuCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c                 sb   t | ƒs	t| tƒrtddd�‚| gˆ¢R ‰tdd„ ˆD ƒƒs$tddd�‚d‡ ‡‡‡‡fd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 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 for the decorated serializer:

    - `(self, value: Any, info: FieldSerializationInfo)`
    - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)`
    - `(value: Any, info: SerializationInfo)`
    - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`

    Args:
        *fields: The field names the serializer should apply to.
        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.

    Raises:
        PydanticUserError:
            - If the decorator is used without any arguments (at least one field name must be provided).
            - If the provided field names are not strings.
    zŸThe `@field_serializer` decorator cannot be used without arguments, at least one field must be provided. For example: `@field_serializer('<field_name>', ...)`.zdecorator-missing-arguments)Úcodec                 s  s   � | ]}t |tƒV  qd S rU   )Ú
isinstancerN   )Ú.0rM   r8   r8   r9   Ú	<genexpr>!  s   € z#field_serializer.<locals>.<genexpr>z›The provided field names to the `@field_serializer` decorator should be strings. For example: `@field_serializer('<field_name_1>', '<field_name_2>', ...).`zdecorator-invalid-fieldsÚfrH   r#   ú(_decorators.PydanticDescriptorProxy[Any]c                   s    t jˆˆˆˆˆ d�}t  | |¡S )N)rO   rP   r   r    rL   )r   ZFieldSerializerDecoratorInfoÚPydanticDescriptorProxy©ra   Zdec_info©rL   rO   rP   r   r    r8   r9   Údec(  s   ûzfield_serializer.<locals>.decN)ra   rH   r#   rb   )Úcallabler^   Úclassmethodr   Úall)rM   rP   r   r    rL   rO   rf   r8   re   r9   rW   à   s   9ýý
ÚModelPlainSerializerWithInfoÚModelPlainSerializerWithoutInfoz>ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfoÚModelPlainSerializerÚModelWrapSerializerWithInfoÚModelWrapSerializerWithoutInfoz<ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfoÚModelWrapSerializerz*ModelPlainSerializer | ModelWrapSerializerÚModelSerializerÚ_ModelPlainSerializerTÚ_ModelWrapSerializerTra   c                C  rT   rU   r8   )ra   r8   r8   r9   Úmodel_serializerP  s   rs   )r    r   ú8Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT]c                 C  rT   rU   r8   ©rP   r    r   r8   r8   r9   rs   T  s   ru   ú:Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]c                 C  rT   rU   r8   ru   r8   r8   r9   rs   Z  s   ú5_ModelPlainSerializerT | _ModelWrapSerializerT | NoneúŽ_ModelPlainSerializerT | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]c                 s&   d‡ ‡‡fdd„}| du r|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}
    ```

    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.
    ra   rp   r#   rb   c                   s   t jˆ ˆˆd�}t  | |¡S )N©rP   r   r    )r   ZModelSerializerDecoratorInforc   rd   ry   r8   r9   rf   £  s   zmodel_serializer.<locals>.decN)ra   rp   r#   rb   r8   )ra   rP   r    r   rf   r8   ry   r9   rs   c  s   @ÚAnyType)r   c                   @  s*   e Zd ZdZddd„Zddd„ZejZdS )ÚSerializeAsAnyzÅAnnotation used to mark a type as having duck-typing serialization behavior.

        See [usage documentation](../concepts/serialization.md#serializing-with-duck-typing) for more details.
        Úitemr   r#   c                 C  s   t |tƒ f S rU   )r   r{   )Úclsr|   r8   r8   r9   Ú__class_getitem__¿  s   z SerializeAsAny.__class_getitem__r!   r"   r   r$   c                 C  sF   ||ƒ}|}|d dkr|  ¡ }|d }|d dkst d¡|d< |S )NÚtypeZdefinitionsr6   Úanyr,   )Úcopyr   Zsimple_ser_schema)r5   r!   r"   r6   Zschema_to_updater8   r8   r9   r:   Â  s   þz+SerializeAsAny.__get_pydantic_core_schema__N)r|   r   r#   r   r<   )r>   r?   r@   rA   r~   r:   ÚobjectÚ__hash__r8   r8   r8   r9   r{   ¸  s
    


r{   )rM   rN   rO   rN   rP   rQ   r   r   r    r   rL   rR   r#   rS   )rM   rN   rO   rN   rP   rY   r   r   r    r   rL   rR   r#   rZ   )rM   rN   rO   rN   rP   r[   r   r   r    r   rL   rR   r#   r\   )ra   rq   r#   rq   )rP   rQ   r    r   r   r   r#   rt   )rP   rY   r    r   r   r   r#   rv   rU   )
ra   rw   rP   r[   r    r   r   r   r#   rx   )9rA   Ú
__future__r   ÚdataclassesÚcollections.abcr   Ú	functoolsr   r   Útypingr   r   r   r	   r
   r   r   Zpydantic_corer   r   Zpydantic_core.core_schemar   r   r   Ztyping_extensionsr   Ú r   Ú	_internalr   Zannotated_handlersr   Úerrorsr   Ú	dataclassr   rC   rE   rB   rF   rG   rH   rI   rK   rW   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rz   r{   r8   r8   r8   r9   Ú<module>   s¢    $E]ùùùUÿü	ÿúJ
