U
    ÓZj©  ã                   @   s†   d Z ddlZddlZddlZddlmZmZ zddlmZm	Z	 W n$ e
k
rd   ddlmZm	Z	 Y nX e ej¡G dd„ deƒƒZdS )zJOSE interfaces.é    N)ÚerrorsÚutil)ÚSequenceÚMappingc                   @   s\   e Zd ZdZejdd„ ƒZdd„ Zej	dd„ ƒZ
edd	„ ƒZd
d„ Zdd„ Zedd„ ƒZdS )ÚJSONDeSerializableaø  Interface for (de)serializable JSON objects.

    Please recall, that standard Python library implements
    :class:`json.JSONEncoder` and :class:`json.JSONDecoder` that perform
    translations based on respective :ref:`conversion tables
    <conversion-table>` that look pretty much like the one below (for
    complete tables see relevant Python documentation):

    .. _conversion-table:

    ======  ======
     JSON   Python
    ======  ======
    object  dict
    ...     ...
    ======  ======

    While the above **conversion table** is about translation of JSON
    documents to/from the basic Python types only,
    :class:`JSONDeSerializable` introduces the following two concepts:

      serialization
        Turning an arbitrary Python object into Python object that can
        be encoded into a JSON document. **Full serialization** produces
        a Python object composed of only basic types as required by the
        :ref:`conversion table <conversion-table>`. **Partial
        serialization** (accomplished by :meth:`to_partial_json`)
        produces a Python object that might also be built from other
        :class:`JSONDeSerializable` objects.

      deserialization
        Turning a decoded Python object (necessarily one of the basic
        types as required by the :ref:`conversion table
        <conversion-table>`) into an arbitrary Python object.

    Serialization produces **serialized object** ("partially serialized
    object" or "fully serialized object" for partial and full
    serialization respectively) and deserialization produces
    **deserialized object**, both usually denoted in the source code as
    ``jobj``.

    Wording in the official Python documentation might be confusing
    after reading the above, but in the light of those definitions, one
    can view :meth:`json.JSONDecoder.decode` as decoder and
    deserializer of basic types, :meth:`json.JSONEncoder.default` as
    serializer of basic types, :meth:`json.JSONEncoder.encode`  as
    serializer and encoder of basic types.

    One could extend :mod:`json` to support arbitrary object
    (de)serialization either by:

      - overriding :meth:`json.JSONDecoder.decode` and
        :meth:`json.JSONEncoder.default` in subclasses

      - or passing ``object_hook`` argument (or ``object_hook_pairs``)
        to :func:`json.load`/:func:`json.loads` or ``default`` argument
        for :func:`json.dump`/:func:`json.dumps`.

    Interestingly, ``default`` is required to perform only partial
    serialization, as :func:`json.dumps` applies ``default``
    recursively. This is the idea behind making :meth:`to_partial_json`
    produce only partial serialization, while providing custom
    :meth:`json_dumps` that dumps with ``default`` set to
    :meth:`json_dump_default`.

    To make further documentation a bit more concrete, please, consider
    the following imaginatory implementation example::

      class Foo(JSONDeSerializable):
          def to_partial_json(self):
              return 'foo'

          @classmethod
          def from_json(cls, jobj):
              return Foo()

      class Bar(JSONDeSerializable):
          def to_partial_json(self):
              return [Foo(), Foo()]

          @classmethod
          def from_json(cls, jobj):
              return Bar()

    c                 C   s
   t ƒ ‚dS )aÖ  Partially serialize.

        Following the example, **partial serialization** means the following::

          assert isinstance(Bar().to_partial_json()[0], Foo)
          assert isinstance(Bar().to_partial_json()[1], Foo)

          # in particular...
          assert Bar().to_partial_json() != ['foo', 'foo']

        :raises josepy.errors.SerializationError:
            in case of any serialization error.
        :returns: Partially serializable object.

        N)ÚNotImplementedError©Úself© r
   úT/var/www/html/TRUCKING_PROJECT/venv/lib/python3.8/site-packages/josepy/interfaces.pyÚto_partial_jsonk   s    z"JSONDeSerializable.to_partial_jsonc                    s   ‡ fdd„‰ ˆ | ƒS )aD  Fully serialize.

        Again, following the example from before, **full serialization**
        means the following::

          assert Bar().to_json() == ['foo', 'foo']

        :raises josepy.errors.SerializationError:
            in case of any serialization error.
        :returns: Fully serialized object.

        c                    s�   t | tƒrˆ |  ¡ ƒS t | tjƒr&| S t | tƒrB‡ fdd„| D ƒS t | tƒrbt‡ fdd„| D ƒƒS t | tƒrˆt	‡ fdd„t 
| ¡D ƒƒS | S d S )Nc                    s   g | ]}ˆ |ƒ‘qS r
   r
   ©Ú.0Zsubobj©Ú
_serializer
   r   Ú
<listcomp>‘   s     zBJSONDeSerializable.to_json.<locals>._serialize.<locals>.<listcomp>c                 3   s   | ]}ˆ |ƒV  qd S ©Nr
   r   r   r
   r   Ú	<genexpr>•   s     zAJSONDeSerializable.to_json.<locals>._serialize.<locals>.<genexpr>c                 3   s"   | ]\}}ˆ |ƒˆ |ƒfV  qd S r   r
   )r   ÚkeyÚvaluer   r
   r   r   —   s   ÿ)Ú
isinstancer   r   ÚsixÚstring_typesÚlistr   Útupler   ÚdictÚ	iteritems)Úobjr   r
   r   r   ‹   s    



ÿz.JSONDeSerializable.to_json.<locals>._serializer
   r   r
   r   r   Úto_json~   s    zJSONDeSerializable.to_jsonc                 C   s   | ƒ S )aÕ  Deserialize a decoded JSON document.

        :param jobj: Python object, composed of only other basic data
            types, as decoded from JSON document. Not necessarily
            :class:`dict` (as decoded from "JSON object" document).

        :raises josepy.errors.DeserializationError:
            if decoding was unsuccessful, e.g. in case of unparseable
            X509 certificate, or wrong padding in JOSE base64 encoded
            string, etc.

        r
   )ÚclsZjobjr
   r
   r   Ú	from_jsonž   s    zJSONDeSerializable.from_jsonc              
   C   sF   zt  |¡}W n, tk
r: } zt |¡‚W 5 d}~X Y nX |  |¡S )z&Deserialize from JSON document string.N)ÚjsonÚloadsÚ
ValueErrorr   ZDeserializationErrorr    )r   Zjson_stringr"   Úerrorr
   r
   r   Ú
json_loads°   s
    zJSONDeSerializable.json_loadsc                 K   s   t j| fd| ji|—ŽS )zsDump to JSON string using proper serializer.

        :returns: JSON document string.
        :rtype: str

        Údefault)r!   ÚdumpsÚjson_dump_default)r	   Úkwargsr
   r
   r   Ú
json_dumps¹   s    zJSONDeSerializable.json_dumpsc                 C   s   | j dddd�S )zNDump the object to pretty JSON document string.

        :rtype: str

        Té   )ú,z: )Ú	sort_keysÚindentÚ
separators)r*   r   r
   r
   r   Újson_dumps_prettyÂ   s    z$JSONDeSerializable.json_dumps_prettyc                 C   s&   t |tƒr| ¡ S tt|ƒd ƒ‚dS )aµ  Serialize Python object.

        This function is meant to be passed as ``default`` to
        :func:`json.dump` or :func:`json.dumps`. They call
        ``default(python_object)`` only for non-basic Python types, so
        this function necessarily raises :class:`TypeError` if
        ``python_object`` is not an instance of
        :class:`IJSONSerializable`.

        Please read the class docstring for more information.

        z is not JSON serializableN)r   r   r   Ú	TypeErrorÚrepr)r   Zpython_objectr
   r
   r   r(   Ê   s    
z$JSONDeSerializable.json_dump_defaultN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚabcÚabstractmethodr   r   r   Úabstractclassmethodr    Úclassmethodr%   r*   r0   r(   r
   r
   r
   r   r      s   V
 

	r   )r6   r7   r!   r   Zjosepyr   r   Úcollections.abcr   r   ÚImportErrorÚcollectionsÚadd_metaclassÚABCMetaÚobjectr   r
   r
   r
   r   Ú<module>   s   
