U
    #i?                  
   @  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 ddlmZmZ ddlmZmZ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f ej ddiG dd dZ!ejf ej ddi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 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d/dd*d!d0d#d$d%d1d2d3d)Z*erTe
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ge	f Z.de$d8< e
e	ege	f Z/de$d9< d:Z0de$d;< d<Z1de$d=< ed>e-dZ2ed?e0dZ3ed>d>d@dAdBZ4ed/ddCd"d$d#dDdEdFdBZ4edd/ddGd+d$d#dHdEdIdBZ4dQd.d/edGdJd0d$d#dKdLdMdBZ4edNZ5eree5df Z6nejf ej G dOdP dPZ6dS )RzEThis module contains related classes and functions for serialization.    )annotationsN)partialpartialmethod)TYPE_CHECKINGAnyCallableTypeVaroverload)PydanticUndefinedcore_schema)SerializationInfoSerializerFunctionWrapHandlerWhenUsed)	AnnotatedLiteral	TypeAlias   )PydanticUndefinedAnnotation)_decorators_internal_dataclass)GetCoreSchemaHandler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 )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alwaysr   	when_usedr   core_schema.CoreSchemasource_typehandlerreturnc              
   C  s   ||}zt | j| j| }W n. tk
rP } zt||W 5 d}~X Y nX |tkr^dn|	|}t
j| jt | jd|| jd|d< |S )zGets the Pydantic core schema.

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

        Returns:
            The Pydantic core schema.
        NplainfunctionZinfo_argreturn_schemar   serialization)r   get_function_return_typer   r   _get_types_namespace	NameErrorr   from_name_errorr
   generate_schemar   Z$plain_serializer_function_ser_schemainspect_annotated_serializerr   selfr   r    schemar   er%    r1   g/var/www/html/me.goteku.com/backend/venv/lib/python3.8/site-packages/pydantic/functional_serializers.py__get_pydantic_core_schema__7   s"    
  
z,PlainSerializer.__get_pydantic_core_schema__N	__name__
__module____qualname____doc____annotations__r
   r   r   r3   r1   r1   r1   r2   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 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 `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   ||}zt | j| j| }W n. tk
rP } zt||W 5 d}~X Y nX |tkr^dn|	|}t
j| jt | jd|| jd|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-   r1   r1   r2   r3      s"    
  
z+WrapSerializer.__get_pydantic_core_schema__Nr4   r1   r1   r1   r2   r:   R   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   rD   r!   c               G  s   d S Nr1   rF   rH   r   r   rD   rG   r1   r1   r2   field_serializer   s    	rK   )rH   r   r   rD   zLiteral['plain']z:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c               G  s   d S rI   r1   rJ   r1   r1   r2   rK      s    	r"   r   zLiteral[('plain', 'wrap')]zuCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT])rG   rH   r   r   rD   r!   c                   s    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 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(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 [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.
    r@   (_decorators.PydanticDescriptorProxy[Any]fr!   c                   s    t j d}t | |S )N)rG   rH   r   r   rD   )r   ZFieldSerializerDecoratorInfoPydanticDescriptorProxyrN   Zdec_inforD   rG   rH   r   r   r1   r2   dec  s    zfield_serializer.<locals>.decr1   )rH   r   r   rD   rG   rR   r1   rQ   r2   rK      s    8
ModelPlainSerializerWithInfoModelPlainSerializerWithoutInfoz>ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfoModelPlainSerializerModelWrapSerializerWithInfoModelWrapSerializerWithoutInfoz<ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfoModelWrapSerializerz*ModelPlainSerializer | ModelWrapSerializerModelSerializer_ModelPlainSerializerT_ModelWrapSerializerTrM   c                C  s   d S rI   r1   )rN   r1   r1   r2   model_serializer;  s    r\   )r   r   z8Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT])rH   r   r   r!   c                 C  s   d S rI   r1   rH   r   r   r1   r1   r2   r\   ?  s    r]   z:Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]c                 C  s   d S rI   r1   r]   r1   r1   r2   r\   E  s    z5_ModelPlainSerializerT | _ModelWrapSerializerT | Nonez_ModelPlainSerializerT | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT])rN   rH   r   r   r!   c                 s0   ddd fdd}| dk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 [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.
    rY   rL   rM   c                   s   t j d}t | |S )NrH   r   r   )r   ZModelSerializerDecoratorInforO   rP   r^   r1   r2   rR     s    zmodel_serializer.<locals>.decNr1   )rN   rH   r   r   rR   r1   r^   r2   r\   N  s    @AnyTypec                   @  s4   e Zd ZdddddZdddddd	ZejZd
S )SerializeAsAnyr   )itemr!   c                 C  s   t |t f S rI   )r   r`   )clsra   r1   r1   r2   __class_getitem__  s    z SerializeAsAny.__class_getitem__r   r   r   c                 C  sH   ||}|}|d dkr*|  }|d }qtjdd t d|d< |S )NtypeZdefinitionsr/   c                 S  s   || S rI   r1   )xhr1   r1   r2   <lambda>      z=SerializeAsAny.__get_pydantic_core_schema__.<locals>.<lambda>)r/   r&   )copyr   r<   Z
any_schema)r.   r   r    r/   Zschema_to_updater1   r1   r2   r3     s    
 
z+SerializeAsAny.__get_pydantic_core_schema__N)r5   r6   r7   rc   r3   object__hash__r1   r1   r1   r2   r`     s   r`   )N)7r8   
__future__r   dataclasses	functoolsr   r   typingr   r   r   r   r	   Zpydantic_corer
   r   Zpydantic_core.core_schemar   r   r   typing_extensionsr   r   r    r   	_internalr   r   Zannotated_handlersr   	dataclassZ
slots_truer   r:   r=   r9   r>   r?   r@   rA   rC   rK   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r_   r`   r1   r1   r1   r2   <module>   s   ?`  E 	 J