
    iF                    &   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!        dSi ej"        ddi G d d                      Z# ej!        dSi ej"        ddi G d d                      Z$er9dZ%de&d<   dZ'de&d<   	 dZ(de&d<   	 dZ)de&d<   	  ede'          Z* ede(          Z+ed d d d!dTd/            Z,ed d d d d0dUd3            Z,d4ed5dd0dVd8Z,eree
ee
         ge
f         Z-de&d9<   	 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><   	 d?Z2de&d@<   	 dAZ3de&dB<    edCe/          Z4 edDe2          Z5edWdF            Z6ed5d dGdXdI            Z6ed d5d dJdYdL            Z6	 dZd4d5edJd[dOZ6 edP          Z7ere	e7d f         Z8dS  ej!        dSi ej"         G dQ dR                      Z8dS )\zEThis 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                  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 )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_usedsource_typehandlerr   returncore_schema.CoreSchemac                    ||          }| j         t          ur| j         }n[	 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.
        localnsNplainfunctioninfo_argreturn_schemar   serialization)r   r   r   get_callable_return_typer   _get_types_namespacelocals	NameErrorr   from_name_errorgenerate_schemar   $plain_serializer_function_ser_schemainspect_annotated_serializerr   selfr    r!   schemar   er+   s          e/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/pydantic/functional_serializers.py__get_pydantic_core_schema__z,PlainSerializer.__get_pydantic_core_schema__6   s    %%#444*KK	L *BI#88::A    L L L1A!DD!KL !,/@ @ @gF]F]^iFjFj"-"RY =diQQ'n	#
 #
 #
    2A 
A: A55A:Nr    r   r!   r   r"   r#   	__name__
__module____qualname____doc____annotations__r   r   r   r:        r9   r   r      sd          : )((((K(((("I""""           rD   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 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   r"   r#   c                    ||          }| j         t          ur| j         }n[	 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.
        r%   Nwrapr(   r,   )r   r   r   r-   r   r.   r/   r0   r   r1   r2   r   #wrap_serializer_function_ser_schemar4   r   r5   s          r9   r:   z+WrapSerializer.__get_pydantic_core_schema__   s    %%#444*KK	L *BI#88::A    L L L1A!DD!KL !,/@ @ @gF]F]^iFjFj"-"QY =diPP'n	#
 #
 #
 r;   Nr<   r=   rC   rD   r9   rF   rF   Y   se         < <| -,,,(K(((("I""""           rD   rF   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   rQ   bool | Noner"   8Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]c                  d S NrC   rR   rU   r   r   rQ   rT   s         r9   field_serializerr\      s     @CsrD   )rU   r   r   rQ   Literal['plain']:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c                  d S rZ   rC   r[   s         r9   r\   r\      s     BErD   r'   r   Literal['plain', 'wrap']uCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c                  t          |           st          | t                    rt          dd          | gR t	          d D                       st          dd          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 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.
    zThe `@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              3  @   K   | ]}t          |t                    V  d S rZ   )
isinstancerS   ).0rR   s     r9   	<genexpr>z#field_serializer.<locals>.<genexpr>*  s,      ::%z%%%::::::rD   zThe 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frM   r"   (_decorators.PydanticDescriptorProxy[Any]c                `    t          j                  }t          j        | |          S )N)rT   rU   r   r   rQ   )r   FieldSerializerDecoratorInfoPydanticDescriptorProxy)rh   dec_inforQ   rT   rU   r   r   s     r9   deczfield_serializer.<locals>.dec1  s>    ;#%
 
 
 21h???rD   )rh   rM   r"   ri   )callablere   classmethodr   all)rR   rU   r   r   rQ   rT   rn   s    ````` r9   r\   r\      s    t  
*UK88 
E.
 
 
 	
 ^V^^F::6::::: 
Y+
 
 
 	
@ @ @ @ @ @ @ @ @ @ JrD   ModelPlainSerializerWithInfoModelPlainSerializerWithoutInfoz>ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfoModelPlainSerializerModelWrapSerializerWithInfoModelWrapSerializerWithoutInfoz<ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfoModelWrapSerializerz*ModelPlainSerializer | ModelWrapSerializerModelSerializer_ModelPlainSerializerT_ModelWrapSerializerTrh   c                   d S rZ   rC   )rh   s    r9   model_serializerr|   Y  s    NQcrD   )r   r   8Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT]c                    d S rZ   rC   rU   r   r   s      r9   r|   r|   ]  s     @CsrD   r   :Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]c                    d S rZ   rC   r   s      r9   r|   r|   c  s     BErD   5_ModelPlainSerializerT | _ModelWrapSerializerT | None_ModelPlainSerializerT | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]c              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}
    ```

    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.
    rh   rx   r"   ri   c                \    t          j                  }t          j        | |          S )N)rU   r   r   )r   ModelSerializerDecoratorInforl   )rh   rm   rU   r   r   s     r9   rn   zmodel_serializer.<locals>.dec  s/    ;S^jsttt21h???rD   N)rh   rx   r"   ri   rC   )rh   rU   r   r   rn   s    ``` r9   r|   r|   l  sO    @@ @ @ @ @ @ @ @ 	y
s1vvrD   AnyTypec                  0    e Zd ZdZddZdd
Zej        ZdS )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.
        itemr   r"   c                8    t           |t                      f         S rZ   )r   r   )clsr   s     r9   __class_getitem__z SerializeAsAny.__class_getitem__  s    T>#3#3344rD   r    r!   r   r#   c                     ||          }|}|d         dk    r(|                                 }|d         }|d         dk    (t          j        d          |d<   |S )Ntypedefinitionsr7   anyr,   )copyr   simple_ser_schema)r6   r    r!   r7   schema_to_updates        r9   r:   z+SerializeAsAny.__get_pydantic_core_schema__  su     W[))F%"6*m;;#3#8#8#:#: #3H#=  #6*m;; 1<0Me0T0T_-MrD   N)r   r   r"   r   r<   )r>   r?   r@   rA   r   r:   object__hash__rC   rD   r9   r   r     sI        	 	
	5 	5 	5 	5		 		 		 		 ?rD   r   rC   )rR   rS   rT   rS   rU   rV   r   r   r   r   rQ   rW   r"   rX   )rR   rS   rT   rS   rU   r]   r   r   r   r   rQ   rW   r"   r^   )rR   rS   rT   rS   rU   r`   r   r   r   r   rQ   rW   r"   ra   )rh   ry   r"   ry   )rU   rV   r   r   r   r   r"   r}   )rU   r]   r   r   r   r   r"   r   rZ   )
rh   r   rU   r`   r   r   r   r   r"   r   )9rA   
__future__r   dataclasses	functoolsr   r   typingr   r   r   r	   r
   r   r   pydantic_corer   r   pydantic_core.core_schemar   r   r   typing_extensionsr    r   	_internalr   r   annotated_handlersr   errorsr   	dataclass
slots_truer   rF   rJ   rB   rK   rL   rM   rN   rP   r\   rr   rs   rt   ru   rv   rw   rx   ry   rz   r|   r   r   rC   rD   r9   <module>r      sk   K K K " " " " " "     , , , , , , , , V V V V V V V V V V V V V V V V V V 8 8 8 8 8 8 8 8 ` ` ` ` ` ` ` ` ` ` ' ' ' ' ' ' ) ) ) ) ) ) 7 7 7 7 7 7 7 7 4 4 4 4 4 4 % % % % % % EE,7EEEEEB B B B B B B FEBJ EE,7EEEEEc c c c c c c FEcL  X=H====&QQQQQ@%TTTTT?!MOMMMM0$W%=EYZZZ#G$;CVWWW 
  #C C C C C 
C 

 ! #E E E E E 
E &-(" $S S S S S Sl  X /7=Ns=S7TVY7Y.Z ZZZZN193%*1E#EEEEQ&fffff4-5s<Y[lmp[q6rtw6w-xxxxxM08#?\9]_b9b0c"ccccP%ccccc3!MOMMMM$W%=EYZZZ#G$;CVWWW 
 Q Q Q 
 Q 
4<QTC C C C C 
C
 
 !"	E E E E E 
E @DG &-"(G G G G G GT ')

  #w|,N  [<<0;<<# # # # # # # =<# # #rD   