U
    d<                  	   @   s  d 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*j.Z.dd Z/d d! Z0d"d# Z1d$d% Z2d&d' Z3d(d) Z4e0  e3  e1  e4  e*5d* e0e3e1e4e0e1e3e4d+Z6e7 Z8e8fd,d-Z9e8fd.d/Z:e:  ed0D ]\Z;Z<e-e;j=fe<  qd3d1d2Z>dS )4zSerialization utilities.    N)
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-hqfrjlvz/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_loads.   s    r-   c                 C   s   | r|  d| dS |S )Nz ()r   )firstsecondr   r   r   parenthesize_alias3   s    r1   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   r3   r4   r:   r;   )r<   namer!   decoderr   r    r   r   r   r   D   s      


zSerializerRegistry.registerc                 C   s"   d|kr| j | }| j| d S N/)r;   r9   discardr<   r?   r   r   r   enablee   s    
zSerializerRegistry.enablec                 C   s"   d|kr| j | }| j| d S rA   )r;   r9   addrD   r   r   r   disablej   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 )zUnregister 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;   r4   popr3   r:   KeyErrorr
   )r<   r?   r   r   r   r   r   o   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)r3   r6   r7   r5   rJ   r
   rD   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.
        rawrK   r   r   r   r'   r>   z
text/plain)
raw_encoder3   getr
   
isinstancebytesstrr)   r	   encoder5   r6   r7   )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_contentr9   lowerr4   rP   r)   r   SKIP_DECODErQ   rS   r   )r<   rU   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   formatr1   r:   rP   )r<   ctypewhyr   r   r   rY     s    z)SerializerRegistry._for_untrusted_content)r>   )N)__name__
__module____qualname____doc__r=   r   rE   rG   r   rL   r   TRUSTED_CONTENTr   rY   r   r   r   r   r2   7   s    
!
@  
.r2   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   rN   r   )rQ   rS   r)   r	   rT   )rU   r   rW   r    r   r   r   rO     s    
rO   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   )jsonrg   application/jsonr>   r   r    N)Zkombu.utilsrg   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yaml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_available8  s    z$register_yaml.<locals>.not_available)rm   rj   r   Z	safe_dumpZ	safe_loadImportError)rm   rs   r   r   r   register_yaml*  s    
ru   c                 C   s   t t| S r*   )r-   r   r+   r   r   r   unpickleC  s    rw   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_dumpsM  s    z%register_pickle.<locals>.pickle_dumpsr   application/x-python-serializer   ri   N)r   r   rj   r   rw   )r{   r   r   r   register_pickleG  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 )zNRegister msgpack serializer.

    See Also:
        https://msgpack.org/.
    Nr   )r   r   packbunpackbc                    s    | ddS )NT)use_bin_typer   rv   )r   r   r   packa  s    zregister_msgpack.<locals>.packc                    s    | ddS )NF)rM   r   rv   )r   r   r   unpackd  s    z register_msgpack.<locals>.unpackc                  _   s   t dd S )Nz(msgpack requires msgpack-python >= 0.4.0ro   rp   r   r   r   version_mismatchg  s    z*register_msgpack.<locals>.version_mismatchc                  _   s   t dd S )NzKNo decoder installed for msgpack. Please install the msgpack-python libraryro   rp   r   r   r   rs   l  s    z'register_msgpack.<locals>.not_availablemsgpackapplication/x-msgpackr   ri   )r   versionr   r   rt   
ValueErrorrj   r   )r   r   r   r   rs   r   r~   r   register_msgpackU  s&    
  r   rg   )rg   r   rm   r   rh   rn   r|   r   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   rE   rJ   )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 )aA  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.
    rg   N)r   rj   r4   rG   rE   )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 )rB   r   ).0nr;   r   r   	<setcomp>  s     z)prepare_accept_content.<locals>.<setcomp>rH   r   )rj   r;   rJ   r
   rq   )Zcontent_typesr;   er   r   r   prepare_accept_content  s    r   )N)?re   r   osr   r#   collectionsr   
contextlibr   ior   
exceptionsr   r   r	   r
   r   Zutils.compatr   Zutils.encodingr   r   __all__	frozensetr[   rf   platform
startswithr   r^   r,   Zpickle_loadintenvironrP   ry   r   	Exceptionr)   r-   r1   r2   rj   r   r   r   r   rO   rl   ru   rw   r}   r   rL   Z
_setupfunsobjectr   r   r   eprq   r?   r   r   r   r   r   <module>   sv   

 
 W	$
