U
    bhV<                     @  s  d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZmZ dZeddgZeddgZejdrdd ZnejZej Z!e"ej#$ddZ%eddZ&e
e'feffddZ(e!fddZ)dd Z*G dd dZ+e+ Z,e,j-Z-e,j.Z.e,j/Z/e,j0Z0dd  Z1d!d" Z2d#d$ Z3d%d& Z4d'd( Z5d)d* Z6e2  e5  e3  e6  e,7d+ e8 Z9e9fd,d-Z:e9fd.d/Z;e;  ed0D ]\Z<Z=e/e<j>fe=  qd3d1d2Z?dS )4zSerialization utilities.    )annotationsN)
namedtuple)contextmanagerBytesIO   )ContentDisallowedDecodeErrorEncodeErrorSerializerNotInstalledreraise)entrypoints)bytes_to_strstr_to_bytes)pickleloadsdumpsregister
unregisterbinaryz
ascii-8bitapplication/datazapplication/textjavac                 C  s   t || d S )Nr   )codecs
getdecoder)tZcoding r   7/tmp/pip-unpacked-wheel-earovzxb/kombu/serialization.py_decode   s    r   ZPICKLE_PROTOCOL   codec)content_typecontent_encodingencoderc              
   c  s^   z
d V  W nN |k
r     Y n: |k
rX } zt | | |t d  W 5 d }~X Y nX d S )N   )r   sysexc_info)wrapperincludeexcludeexcr   r   r   _reraise_errors%   s    
r*   c                 C  s   |t | S Nr   )sloadr   r   r   pickle_loads0   s    r.   c                 C  s   | r|  d| dS |S )Nz ()r   )firstsecondr   r   r   parenthesize_alias5   s    r2   c                   @  sd   e Zd ZdZdd ZdddZdd Zd	d
 Zdd Zdd Z	dddZ
ddefddZdd ZdS )SerializerRegistryz2The registry keeps track of serialization methods.c                 C  s6   i | _ i | _d | _d | _d | _t | _i | _i | _d S r+   )		_encoders	_decoders_default_encode_default_content_type_default_content_encodingset_disabled_content_typestype_to_namename_to_type)selfr   r   r   __init__<   s    zSerializerRegistry.__init__utf-8c                 C  s<   |rt |||| j|< |r$|| j|< || j|< || j|< dS )a  Register a new encoder/decoder.

        Arguments:
        ---------
            name (str): A convenience name for the serialization method.

            encoder (callable): A method that will be passed a python data
                structure and should return a string representing the
                serialized data.  If :const:`None`, then only a decoder
                will be registered. Encoding will not be possible.

            decoder (Callable): A method that will be passed a string
                representing serialized data and should return a python
                data structure.  If :const:`None`, then only an encoder
                will be registered.  Decoding will not be possible.

            content_type (str): The mime-type describing the serialized
                structure.

            content_encoding (str): The content encoding (character set) that
                the `decoder` method will be returning. Will usually be
                `utf-8`, `us-ascii`, or `binary`.
        N)r   r4   r5   r;   r<   )r=   namer"   decoderr    r!   r   r   r   r   F   s      


zSerializerRegistry.registerc                 C  s"   d|kr| j | }| j| d S N/)r<   r:   discardr=   r@   r   r   r   enableh   s    
zSerializerRegistry.enablec                 C  s"   d|kr| j | }| j| d S rB   )r<   r:   addrE   r   r   r   disablem   s    
zSerializerRegistry.disablec                 C  sn   zF| j | }| j|d | j|d | j|d | j |d W n" tk
rh   td| Y nX dS )a  Unregister registered encoder/decoder.

        Arguments:
        ---------
            name (str): Registered serialization method name.

        Raises
        ------
            SerializerNotInstalled: If a serializer by that name
                cannot be found.
        N!No encoder/decoder installed for )r<   r5   popr4   r;   KeyErrorr   )r=   r@   r    r   r   r   r   r   s    
zSerializerRegistry.unregisterc                 C  sB   z| j | \| _| _| _W n" tk
r<   td| Y nX dS )a  Set the default serialization method used by this library.

        Arguments:
        ---------
            name (str): The name of the registered serialization method.
                For example, `json` (default), `pickle`, `yaml`, `msgpack`,
                or any custom methods registered using :meth:`register`.

        Raises
        ------
            SerializerNotInstalled: If the serialization method
                requested is not available.
        No encoder installed for N)r4   r7   r8   r6   rK   r   rE   r   r   r   _set_default_serializer   s    
z*SerializerRegistry._set_default_serializerNc              	   C  s   |dkrt |S |r.| j|s.td| |sFt|trFdd|fS |st|trttdd |	d}W 5 Q R X dd|fS |r| j| \}}}n| j
}| j}| j}tt ||}W 5 Q R X |||fS )	a  Encode data.

        Serialize a data structure into a string suitable for sending
        as an AMQP message body.

        Arguments:
        ---------
            data (List, Dict, str): The message data to send.

            serializer (str): An optional string representing
                the serialization method you want the data marshalled
                into. (For example, `json`, `raw`, or `pickle`).

                If :const:`None` (default), then json will be used, unless
                `data` is a :class:`str` or :class:`unicode` object. In this
                latter case, no serialization occurs as it would be
                unnecessary.

                Note that if `serializer` is specified, then that
                serialization method will be used even if a :class:`str`
                or :class:`unicode` object is passed in.

        Returns
        -------
            Tuple[str, str, str]: A three-item tuple containing the
            content type (e.g., `application/json`), content encoding, (e.g.,
            `utf-8`) and a string containing the serialized data.

        Raises
        ------
            SerializerNotInstalled: If the serialization method
                requested is not available.
        rawrL   r   r   r   r(   r?   z
text/plain)
raw_encoder4   getr   
isinstancebytesstrr*   r
   encoder6   r7   r8   )r=   data
serializerpayloadr    r!   r"   r   r   r   r      s*    "



zSerializerRegistry.dumpsFc              
   C  s   |rt |nd}|dk	r6||krP||krP| |dn|| jkrP|sP| |d|pVd }|r| j|}|rtt ||W  5 Q R  S Q R X |tkrt	|t
stt t||W  5 Q R  S Q R X |S )a  Decode serialized data.

        Deserialize a data stream as serialized using `dumps`
        based on `content_type`.

        Arguments:
        ---------
            data (bytes, buffer, str): The message data to deserialize.

            content_type (str): The content-type of the data.
                (e.g., `application/json`).

            content_encoding (str): The content-encoding of the data.
                (e.g., `utf-8`, `binary`, or `us-ascii`).

            accept (Set): List of content-types to accept.

        Raises
        ------
            ContentDisallowed: If the content-type is not accepted.

        Returns
        -------
            Any: The unserialized data.
        r   NZ	untrusteddisabledr?   )r   _for_untrusted_contentr:   lowerr5   rQ   r*   r	   SKIP_DECODErR   rT   r   )r=   rV   r    r!   acceptforceZ_trusted_contentdecoder   r   r   r      s,    

zSerializerRegistry.loadsc              	   C  s    t d|t| j|||S )Nz-Refusing to deserialize {} content of type {})r   formatr2   r;   rQ   )r=   ctypewhyr   r   r   rZ     s    z)SerializerRegistry._for_untrusted_content)r?   )N)__name__
__module____qualname____doc__r>   r   rF   rH   r   rM   r   TRUSTED_CONTENTr   rZ   r   r   r   r   r3   9   s    
"
C  
1r3   c              	   C  sH   d}| }t |tr:d}ttdd ||}W 5 Q R X nd}|||fS )zSpecial case serializer.r   r?   r   rO   r   )rR   rT   r*   r
   rU   )rV   r    rX   r!   r   r   r   rP   !  s    
rP   c                  C  s(   ddl m}  tjd| j| jddd dS )z2Register a encoder/decoder for JSON serialization.r   )jsonrh   zapplication/jsonr?   r    r!   N)Zkombu.utilsrh   registryr   r   r   )_jsonr   r   r   register_json.  s
    rl   c               	   C  sV   z$ddl } tjd| j| jddd W n, tk
rP   dd }tdd|d Y nX dS )	zRegister a encoder/decoder for YAML serialization.

    It is slower than JSON, but allows for more data types
    to be serialized. Useful if you need to send data such as dates

    r   Nyamlzapplication/x-yamlr?   ri   c                  _  s   t ddS )zRaise SerializerNotInstalled.

            Used in case a client receives a yaml message, but yaml
            isn't installed.
            z9No decoder installed for YAML. Install the PyYAML libraryNr   argskwargsr   r   r   not_availableE  s    z$register_yaml.<locals>.not_available)rm   rj   r   Z	safe_dumpZ	safe_loadImportError)rm   rr   r   r   r   register_yaml7  s    
rt   c                 C  s   t t| S r+   )r.   r   r,   r   r   r   unpickleP  s    rv   c                  C  s&   t jfdd} tjd| tddd dS )zpRegister pickle serializer.

    The fastest serialization method, but restricts
    you to python clients.
    c                 S  s   || t dS )N)protocol)pickle_protocol)objZdumperr   r   r   pickle_dumpsZ  s    z%register_pickle.<locals>.pickle_dumpsr   zapplication/x-python-serializer   ri   N)r   r   rj   r   rv   )rz   r   r   r   register_pickleT  s
    
r{   c               	     s   d } }zPddl }|jdkrFddl m m  fdd} fdd}nd	d
 }| } }W n( ttfk
r   dd }| } }Y nX tjd| |ddd dS )zZRegister msgpack serializer.

    See Also
    --------
        https://msgpack.org/.
    Nr   )r   r   packbunpackbc                   s    | ddS )NT)use_bin_typer   ru   )r}   r   r   packo  s    zregister_msgpack.<locals>.packc                   s    | ddS )NF)rN   r   ru   )r~   r   r   unpackr  s    z register_msgpack.<locals>.unpackc                  _  s   t dd S )Nz(msgpack requires msgpack-python >= 0.4.0rn   ro   r   r   r   version_mismatchu  s    z*register_msgpack.<locals>.version_mismatchc                  _  s   t dd S )NzKNo decoder installed for msgpack. Please install the msgpack-python libraryrn   ro   r   r   r   rr   z  s    z'register_msgpack.<locals>.not_availablemsgpackzapplication/x-msgpackr   ri   )r   versionr}   r~   rs   
ValueErrorrj   r   )r   r   r   r   rr   r   r|   r   register_msgpackb  s&    
  r   rh   c              	   C  sP   | t krdddgn| } | dk	rL| D ](}zt| W q" tk
rH   Y q"X q"dS )zEnable serializers that are considered to be unsafe.

    Note:
    ----
        Will enable ``pickle``, ``yaml`` and ``msgpack`` by default, but you
        can also specify a list of serializers (by name or content type)
        to enable.
    r   rm   r   N)NOTSETrj   rF   rK   )choiceschoicer   r   r   enable_insecure_serializers  s    	r   c                 C  sH   | t krdgn| } tjD ]}t| q| dk	rD| D ]}t| q4dS )aJ  Disable untrusted serializers.

    Will disable all serializers except ``json``
    or you can specify a list of deserializers to allow.

    Note:
    ----
        Producers will still be able to serialize data
        in these formats, but consumers will not accept
        incoming data using the untrusted content types.
    rh   N)r   rj   r5   rH   rF   )allowedr@   r   r   r   disable_insecure_serializers  s    
r   zkombu.serializersc              
     sf    s
t jn  | dk	rbz fdd| D W S  tk
r` } ztd|jd  W 5 d}~X Y nX | S )zReplace aliases of content_types with full names from registry.

    Raises
    ------
        SerializerNotInstalled: If the serialization method
            requested is not available.
    Nc                   s    h | ]}d |kr|n | qS )rC   r   ).0nr<   r   r   	<setcomp>  s     z)prepare_accept_content.<locals>.<setcomp>rI   r   )rj   r<   rK   r   rp   )Zcontent_typesr<   er   r   r   prepare_accept_content  s    r   )N)@rf   
__future__r   r   osr   r$   collectionsr   
contextlibr   ior   
exceptionsr   r	   r
   r   r   Zutils.compatr   Zutils.encodingr   r   __all__	frozensetr\   rg   platform
startswithr   r_   r-   Zpickle_loadintenvironrQ   rx   r   	Exceptionr*   r.   r2   r3   rj   r   r   r   r   rP   rl   rt   rv   r{   r   rM   objectr   r   r   eprp   r@   r   r   r   r   r   <module>   sf   

 
 b	%
