Spade

Mini Shell

Directory:~$ /proc/self/root/lib/python2.7/site-packages/josepy/
Upload File

[Home] [System Details] [Kill Me]
Current File:~$ //proc/self/root/lib/python2.7/site-packages/josepy/json_util.pyo

�
�t0^c@s>dZddlZddlZddlZddlZddlZddlmZmZm	Z	m
Z
eje�Z
defd��YZdejfd��YZeje�de
je	jfd	��Y�Zd
�Zded�Zd�Zded
�Zd�Zd�Zd�Zd�Zdefd��YZ
dS(s�JSON (de)serialization framework.

The framework presented here is somewhat based on `Go's
"json" package`_
(especially the ``omitempty`` functionality).

.. _`Go's "json" package`:
http://golang.org/pkg/encoding/json/

i����N(tb64terrorst
interfacestutiltFieldcBs�eZdZdZdeddd�Zed��Zd�Z	d	�Z
d
�Zd�Zd�Z
d
�Zed��Zed��ZRS(s�JSON object
field.

    :class:`Field` is meant to be used together with
    :class:`JSONObjectWithFields`.

    ``encoder`` (``decoder``) is a callable that accepts a single
    parameter, i.e. a value to be encoded (decoded), and returns the
    serialized (deserialized) value. In case of errors it should raise
    :class:`~josepy.errors.SerializationError`
    (:class:`~josepy.errors.DeserializationError`).

    Note, that ``decoder`` should perform partial serialization only.

    :ivar str json_name: Name of the field when encoded to JSON.
    :ivar default: Default value (used when not present in JSON object).
    :ivar bool omitempty: If ``True`` and the field value is empty, then
        it will not be included in the serialized JSON object, and
        ``default`` will be used for deserialization. Otherwise, if
``False``,
        field is considered as required, value will always be included in
the
        serialized JSON objected, and it must also be present when
        deserializing.

   
t	json_nametdefaultt	omitemptytfdectfenccCs[||_||_||_|dkr0|jn||_|dkrN|jn||_dS(N(RRRtNonetdefault_decoderRtdefault_encoderR	(tselfRRRtdecodertencoder((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt__init__/s
			cCst|t�o|S(s�Is the provided value considered
"empty" for this field?

        This is useful for subclasses that might want to override the
        definition of being empty, e.g. for some more exotic data types.

        (t
isinstancetbool(tclstvalue((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt_empty9scCs|j|�o|jS(sOmit
the value in
output?(RR(R
R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytomitCscKsStd|jd|jd|jd|jd|j�}|j|�t|�|�S(NRRRRR(tdictRRRRR	tupdatettype(R
tkwargstcurrent((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt_update_paramsGs
	
cCs|jd|�S(s6Descriptor to change the decoder on JSON
object
field.R(R(R
R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRNscCs|jd|�S(s6Descriptor
to change the encoder on JSON object
field.R(R(R
R	((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRRscCs
|j|�S(s4Decode
a value, optionally with context JSON
object.(R(R
R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytdecodeVscCs
|j|�S(s4Encode
a value, optionally with context JSON
object.(R	(R
R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytencodeZscslt|t�r)t�fd�|D��St|t�rdtjt�fd�tj|�D���S|SdS(s�Default
decoder.

        Recursively deserialize into immutable types (
        :class:`josepy.util.frozendict` instead of
        :func:`dict`, :func:`tuple` instead of :func:`list`).

       
c3s|]}�j|�VqdS(N(R(t.0tsubvalue(R(s4/usr/lib/python2.7/site-packages/josepy/json_util.pys	<genexpr>isc3s3|])\}}�j|��j|�fVqdS(N(R(RtkeyR(R(s4/usr/lib/python2.7/site-packages/josepy/json_util.pys	<genexpr>lsN(RtlistttupleRRt
frozendicttsixt	iteritems(RR((Rs4/usr/lib/python2.7/site-packages/josepy/json_util.pyR^s
cCs|S(sDefault (passthrough)
encoder.((RR((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRqs(s	json_namesdefaults	omitemptysfdecsfencN(t__name__t
__module__t__doc__t	__slots__R
tFalseRtclassmethodRRRRRRRRR(((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRs	
						tJSONObjectWithFieldsMetacBseZdZd�ZRS(s�Metaclass
for :class:`JSONObjectWithFields` and its subclasses.

    It makes sure that, for any class ``cls`` with ``__metaclass__``
    set to ``JSONObjectWithFieldsMeta``:

    1. All fields (attributes of type :class:`Field`) in the class
       definition are moved to the ``cls._fields`` dictionary, where
       keys are field attribute names and values are fields themselves.

    2. ``cls.__slots__`` is extended by all field attribute names
       (i.e. not :attr:`Field.json_name`). Original ``cls.__slots__``
       are stored in ``cls._orig_slots``.

    In a consequence, for a field attribute name ``some_field``,
    ``cls.some_field`` will be a slot descriptor and not an instance
    of :class:`Field`. For example::

      some_field = Field('someField', default=())

      class Foo(object):
          __metaclass__ = JSONObjectWithFieldsMeta
          __slots__ = ('baz',)
          some_field = some_field

      assert Foo.__slots__ == ('some_field', 'baz')
      assert Foo._orig_slots == ()
      assert Foo.some_field is not Field

      assert Foo._fields.keys() == ['some_field']
      assert Foo._fields['some_field'] is some_field

    As an implementation note, this metaclass inherits from
    :class:`abc.ABCMeta` (and not the usual :class:`type`) to mitigate
    the metaclass conflict (:class:`ImmutableMap` and
    :class:`JSONDeSerializable`, parents of :class:`JSONObjectWithFields`,
    use :class:`abc.ABCMeta` as its metaclass).

   
cCs�i}x'|D]}|jt|di��q
WxHttj|��D]1\}}t|t�rF|j|�||<qFqFW|jdd�|d<tt	|d�t	tj
|���|d<||d<tjj
||||�S(Nt_fieldsR*t_orig_slots((RtgetattrR#R%R&RRtpoptgetR"titerkeystabctABCMetat__new__(tmcstnametbasestdikttfieldstbaseR!R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyR6�s
"*
(R'R(R)R6(((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyR-ys&tJSONObjectWithFieldscBsneZdZed��Zd�Zd�Zd�Zd�Zed��Z	ed��Z
ed��ZRS(	s�JSON object with fields.

    Example::

      class Foo(JSONObjectWithFields):
          bar = Field('Bar')
          empty = Field('Empty', omitempty=True)

          @bar.encoder
          def bar(value):
              return value + 'bar'

          @bar.decoder
          def bar(value):
              if not value.endswith('bar'):
                  raise errors.DeserializationError('No bar
suffix!')
              return value[:-3]

      assert Foo(bar='baz').to_partial_json() ==
{'Bar': 'bazbar'}
      assert Foo.from_json({'Bar': 'bazbar'}) ==
Foo(bar='baz')
      assert (Foo.from_json({'Bar': 'bazbar',
'Empty': '!'})
              == Foo(bar='baz', empty='!'))
      assert Foo(bar='baz').bar == 'baz'

    cCs8tgtj|j�D]\}}||jf^q�S(sGet default fields
values.(RR%R&R.R(Rtslottfield((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt	_defaults�scKs)tt|�jt|j�|��dS(N(tsuperR=RRR@(R
R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyR�scCsSy|j|}Wn)tk
r<tjdj|���nX|jt||��S(s�Encode a single
field.

        :param str name: Name of the field to be encoded.

        :raises errors.SerializationError: if field cannot be serialized
        :raises errors.Error: if field could not be found

        sField not found:
{0}(R.tKeyErrorRtErrortformatRR0(R
R8R?((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyR�s
	
cCs�i}t�}x�tj|j�D]�\}}t||�}|j|�rb|j||f�q"y|j|�||j<Wq"t	j
k
r�}t	j
dj|||���q"Xq"W|S(sSerialize fields to
JSON.sCould not encode {0} ({1}):
{2}(tsetR%R&R.R0RtaddRRRtSerializationErrorRD(R
tjobjtomittedR>R?Rterror((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytfields_to_partial_json�s	cCs
|j�S(N(RK(R
((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytto_partial_json�scCs�t�}xLtj|j�D]8\}}|jr|j|kr|j|j�qqW|r�tjdj	dj
|����ndS(Ns&The following fields are required:
{0}t,(RER%R&R.RRRFRtDeserializationErrorRDtjoin(RRHtmissingt_R?((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt_check_requireds	cCs�|j|�i}x�tj|j�D]�\}}|j|krZ|jrZ|j||<q&||j}y|j|�||<Wq&tj	k
r�}tj	dj
|||���q&Xq&W|S(sDeserialize fields from JSON.s#Could
not decode {0!r} ({1!r}):
{2}(RRR%R&R.RRRRRRNRD(RRHR;R>R?RRJ((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytfields_from_json
s

cCs||j|��S(N(RS(RRH((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt	from_jsons(R'R(R)R,R@RRRKRLRRRSRT(((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyR=�s				cCstj|�jd�S(sNEncode
JOSE Base-64 field.

    :param bytes data:
    :rtype: `unicode`

   
tascii(Rt	b64encodeR(tdata((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytencode_b64jose$scCs�tjrtntj}ytj|j��}Wn"|k
rU}tj	|��nX|dk	r�|r{t|�|ks�|r�t|�|kr�tj	dj|���n|S(sDecode
JOSE Base-64 field.

    :param unicode data:
    :param int size: Required length (after decoding).
    :param bool minimum: If ``True``, then `size` will be treated as
        minimum required length, as opposed to exact equality.

    :rtype: bytes

    s&Expected at least or exactly {0}
bytesN(
R%tPY2t	TypeErrortbinasciiRCRt	b64decodeRRRNR
tlenRD(RWtsizetminimumt	error_clstdecodedRJ((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytdecode_b64jose/s%cCstj|�j�S(s;Hexlify.

    :param bytes value:
    :rtype: unicode

   
(R[thexlifyR(R((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytencode_hex16Hsc	Cs�|j�}|dk	r`|r5t|�|dksQ|r`t|�|dkr`tj��ntjrotntj	}ytj
|�SWn"|k
r�}tj|��nXdS(sDecode hexlified field.

    :param unicode value:
    :param int size: Required length (after decoding).
    :param bool minimum: If ``True``, then `size` will be treated as
        minimum required length, as opposed to exact equality.

    :rtype: bytes

    iN(RR
R]RRNR%RYRZR[RCt	unhexlify(RR^R_R`RJ((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytdecode_hex16Rs)cCs"ttjjtjj|j��S(s�Encode
certificate as JOSE Base-64 DER.

    :type cert: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
    :rtype: unicode

   
(RXtOpenSSLtcryptotdump_certificatet
FILETYPE_ASN1twrapped(tcert((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytencode_certhscCs[y,tjtjjtjjt|���SWn(tjjk
rV}tj	|��nXdS(s�Decode JOSE Base-64 DER-encoded
certificate.

    :param unicode b64der:
    :rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`

    N(
RtComparableX509RgRhtload_certificateRjRbRCRRN(tb64derRJ((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytdecode_certss
cCs"ttjjtjj|j��S(sEncode CSR as JOSE
Base-64 DER.

    :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`
    :rtype: unicode

   
(RXRgRhtdump_certificate_requestRjRk(tcsr((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt
encode_csr�scCs[y,tjtjjtjjt|���SWn(tjjk
rV}tj	|��nXdS(s�Decode JOSE Base-64 DER-encoded CSR.

    :param unicode b64der:
    :rtype: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`

    N(
RRnRgRhtload_certificate_requestRjRbRCRRN(RpRJ((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt
decode_csr�s
tTypedJSONObjectWithFieldscBsYeZdZeZdZeZedd��Z	ed��Z
d�Zed��ZRS(sJSON object with
type.RcCs,|dkr|jn|}||j|<|S(s(Register class for JSON
deserialization.N(R
ttyptTYPES(Rttype_clsRx((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytregister�s
cCs�|tj|j�krI|j|krEtjdj|j���n|St|t�sstjdj|���ny||j}Wn
t	k
r�tjd��nXy|j|SWn#t	k
r�tj
||��nXdS(s&Get the registered class for ``jobj``.sMissing
type field ({0})s{0} is not a dictionary objectsmissing type fieldN(R%t
itervaluesRyttype_field_nameRRNRDRRRBtUnrecognizedTypeError(RRHRx((s4/usr/lib/python2.7/site-packages/josepy/json_util.pytget_type_cls�s


cCs |j�}|j||j<|S(sGet JSON
serializable object.

        :returns: Serializable JSON object representing ACME typed object.
            :meth:`validate` will almost certainly not work, due to reasons
            explained in :class:`josepy.interfaces.IJSONSerializable`.
        :rtype: dict

       
(RKRxR}(R
RH((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRL�s	cCs"|j|�}||j|��S(s�Deserialize
ACME object from valid JSON object.

        :raises josepy.errors.UnrecognizedTypeError: if type
            of the ACME object has not been registered.

       
(RRS(RRHRz((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRT�s	N(
R'R(R)tNotImplementedRxR}RyR,R
R{RRLRT(((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyRw�s	
(!R)R4R[tloggingRgR%tjosepyRRRRt	getLoggerR'tloggertobjectRR5R-t
add_metaclasstImmutableMaptJSONDeSerializableR=RXR
R+RbRdRfRmRqRtRvRw(((s4/usr/lib/python2.7/site-packages/josepy/json_util.pyt<module>s("d;o