a
    “˜ëjÅF  ã                
   @  s*  U d Z ddlmZ ddl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mZ d	dlmZ d	dlm Z  ej!f i ej"¤ddi¤ŽG dd„ dƒƒZ#ej!f i ej"¤ddi¤ŽG dd„ dƒƒZ$e�rPd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!œd"d"d#d$d%d&d'd(œd)d*„ƒZ,ed d d d d+œd"d"d,d$d%d&d-d(œd.d*„ƒZ,d/ed0dd+œd"d"d1d$d%d&d2d(œd3d*„Z,e�rree
ee
 ge
f Z-de&d4< ee
ge
f Z.de&d5< d6Z/de&d7< ee
eee
 ge
f Z0de&d8< ee
ege
f Z1de&d9< d:Z2de&d;< d<Z3de&d=< ed>e/d�Z4ed?e2d�Z5ed>d>d@œdAdB„ƒZ6ed0d dCœd#d%d$dDdEœdFdB„ƒZ6ed d0d dGœd,d%d$dHdEœdIdB„ƒZ6dQd/d0edGœdJd1d%d$dKdLœdMdB„Z6edNƒZ7e�re	e7d f Z8n ej!f i ej"¤ŽG dOdP„ dPƒƒZ8dS )RzEThis module contains related classes and functions for serialization.é    )ÚannotationsN)ÚpartialÚpartialmethod)ÚTYPE_CHECKINGÚ	AnnotatedÚAnyÚCallableÚLiteralÚTypeVarÚoverload)ÚPydanticUndefinedÚcore_schema)ÚSerializationInfoÚSerializerFunctionWrapHandlerÚWhenUsed)Ú	TypeAliasé   )ÚPydanticUndefinedAnnotation)Ú_decoratorsÚ_internal_dataclass)ÚGetCoreSchemaHandler)ÚPydanticUserErrorÚfrozenTc                   @  sD   e Zd ZU dZded< eZded< dZded< dd	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Úfuncr   Úreturn_typeÚalwaysr   Ú	when_usedr   úcore_schema.CoreSchema©Úsource_typeÚhandlerÚreturnc              
   C  s¤   ||ƒ}| j tur| j }nLztj| j| ¡ jd�}W n0 tyd } zt 	|¡|‚W Y d}~n
d}~0 0 |tu rrd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(   © r5   ú^/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pydantic/functional_serializers.pyÚ__get_pydantic_core_schema__6   s$    

þ
"ü
z,PlainSerializer.__get_pydantic_core_schema__N©	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r   r7   r5   r5   r5   r6   r      s
   
r   c                   @  sD   e Zd ZU dZded< eZded< dZded< dd	d
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 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.WrapSerializerFunctionr   r   r   r   r   r   r   r   r   c              
   C  s¤   ||ƒ}| j tur| j }nLztj| j| ¡ jd�}W n0 tyd } zt 	|¡|‚W Y d}~n
d}~0 0 |tu rrdn| 
|¡}tj| jt | jd¡|| jd�|d< |S )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,   r-   r   r.   r/   r   Z#wrap_serializer_function_ser_schemar0   r   r1   r5   r5   r6   r7   �   s$    

þ
"ü
z+WrapSerializer.__get_pydantic_core_schema__Nr8   r5   r5   r5   r6   r>   Y   s
   
>r>   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ÚstrzLiteral['wrap']r   r   zbool | Nonez8Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT])ÚfieldÚfieldsÚmoder   r   rG   r"   c               G  s   d S ©Nr5   ©rI   rK   r   r   rG   rJ   r5   r5   r6   Úfield_serializerÐ   s    	rN   )rK   r   r   rG   zLiteral['plain']z:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c               G  s   d S rL   r5   rM   r5   r5   r6   rN   Ü   s    	r%   r   zLiteral['plain', 'wrap']zuCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c                 sh   t | ƒst| tƒrtddd�‚| gˆ¢R ‰tdd„ ˆD ƒƒsHtdd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 rL   )Ú
isinstancerH   )Ú.0rI   r5   r5   r6   Ú	<genexpr>*  ó    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-fieldsrC   ú(_decorators.PydanticDescriptorProxy[Any]©Úfr"   c                   s    t jˆˆˆˆˆ d�}t  | |¡S )N)rJ   rK   r   r   rG   )r   ZFieldSerializerDecoratorInfoÚPydanticDescriptorProxy©rV   Zdec_info©rG   rJ   rK   r   r   r5   r6   Údec1  s    ûzfield_serializer.<locals>.dec)ÚcallablerP   Úclassmethodr   Úall)rI   rK   r   r   rG   rJ   rZ   r5   rY   r6   rN   è   s    :ýý
ÚModelPlainSerializerWithInfoÚModelPlainSerializerWithoutInfoz>ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfoÚModelPlainSerializerÚModelWrapSerializerWithInfoÚModelWrapSerializerWithoutInfoz<ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfoÚModelWrapSerializerz*ModelPlainSerializer | ModelWrapSerializerÚModelSerializerÚ_ModelPlainSerializerTÚ_ModelWrapSerializerTrU   c                C  s   d S rL   r5   )rV   r5   r5   r6   Úmodel_serializerY  s    rg   )r   r   z8Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT])rK   r   r   r"   c                 C  s   d S rL   r5   ©rK   r   r   r5   r5   r6   rg   ]  s    rh   z:Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]c                 C  s   d S rL   r5   rh   r5   r5   r6   rg   c  s    z5_ModelPlainSerializerT | _ModelWrapSerializerT | NonezŽ_ModelPlainSerializerT | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT])rV   rK   r   r   r"   c                 s0   dddœ‡ ‡‡fdd„}| du r$|S || ƒS d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.
    rd   rT   rU   c                   s   t jˆ ˆˆd�}t  | |¡S )N©rK   r   r   )r   ZModelSerializerDecoratorInforW   rX   ri   r5   r6   rZ   ¬  s    zmodel_serializer.<locals>.decNr5   )rV   rK   r   r   rZ   r5   ri   r6   rg   l  s    @ÚAnyTypec                   @  s8   e Zd ZdZdddœdd„Zddd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.
        r   )Úitemr"   c                 C  s   t |tƒ f S rL   )r   rk   )Úclsrl   r5   r5   r6   Ú__class_getitem__È  s    z SerializeAsAny.__class_getitem__r   r   r   c                 C  s<   ||ƒ}|}|d dkr*|  ¡ }|d }qt d¡|d< |S )NÚtypeZdefinitionsr3   Úanyr)   )Úcopyr   Zsimple_ser_schema)r2   r    r!   r3   Zschema_to_updater5   r5   r6   r7   Ë  s    
z+SerializeAsAny.__get_pydantic_core_schema__N)r9   r:   r;   r<   rn   r7   ÚobjectÚ__hash__r5   r5   r5   r6   rk   Á  s   rk   )N)9r<   Ú
__future__r   ZdataclassesÚ	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   r   Zannotated_handlersr   Úerrorsr   Z	dataclassZ
slots_truer   r>   r@   r=   rA   rB   rC   rD   rF   rN   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rj   rk   r5   r5   r5   r6   Ú<module>   sŒ   $Efù ù øVÿü	 ÿúJ