
_.                 @   s  d  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
 d d l m Z d d	 l m Z d d
 l m Z d d l m Z d d l m Z y d d l Z Wn e k
 r d Z Yn Xd e j d  k Z d d d d d d d d d g	 Z d d   Z d d   Z Gd d   d e j  Z Gd d   d e j  Z d d d  Z d d  d!  Z d" d#   Z d d$ d  Z d d% d  Z d d& d  Z  d d' d  Z! d( d   Z" d) d   Z# d* d   Z$ d+ d,   Z% d S)-zH
flask.json
~~~~~~~~~~

:copyright: 2010 Pallets
:license: BSD-3-Clause
    N)date)datetime)json)Markup)	http_date   )PY2)	text_type)current_app)requestz\//dumpdumpsloadloadshtmlsafe_dumphtmlsafe_dumpsJSONDecoderJSONEncoderjsonifyc             C   s7   t  |  j d  t  r3 t j t j |   |  }  |  S)Nr   )
isinstancereadbytesioTextIOWrapperBufferedReader)fpencoding r   4/tmp/pip-build-5gj8f0j9/flask/flask/json/__init__.py_wrap_reader_for_text/   s    r    c             C   s<   y |  j  d  Wn$ t k
 r7 t j |  |  }  Yn X|  S)N )write	TypeErrorr   r   )r   r   r   r   r   _wrap_writer_for_text5   s
    r$   c               @   s"   e  Z d  Z d Z d d   Z d S)r   al  The default Flask JSON encoder. This one extends the default
    encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,
    and ``Markup`` objects.

    ``datetime`` objects are serialized as RFC 822 datetime strings.
    This is the same as the HTTP date format.

    In order to support more data types, override the :meth:`default`
    method.
    c             C   s   t  | t  r t | j    St  | t  r> t | j    St  | t j  rZ t |  St	 r| t	 j
 |  r| t	 j |  St | d  r t | j    St j j |  |  S)a&  Implement this method in a subclass such that it returns a
        serializable object for ``o``, or calls the base implementation (to
        raise a :exc:`TypeError`).

        For example, to support arbitrary iterators, you could implement
        default like this::

            def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                return JSONEncoder.default(self, o)
        __html__)r   r   r   utctimetupler   	timetupleuuidUUIDstrdataclassesZis_dataclassZasdicthasattrr	   r%   _jsonr   default)selfor   r   r   r.   I   s    
zJSONEncoder.defaultN)__name__
__module____qualname____doc__r.   r   r   r   r   r   =   s   
c               @   s   e  Z d  Z d Z d S)r   a  The default JSON decoder.  This one does not change the behavior from
    the default simplejson decoder.  Consult the :mod:`json` documentation
    for more information.  This decoder is not only used for the load
    functions of this module but also :attr:`~flask.Request`.
    N)r1   r2   r3   r4   r   r   r   r   r   g   s   c             C   s   | d k r t  } | r t r3 | j j t j  n d } |  j d | rZ | j rZ | j n | j  | j d s |  j d d  |  j d | j d  n  |  j d d  |  j d t  d S)	z,Inject default arguments for dump functions.NclsZJSON_AS_ASCIIensure_asciiF	sort_keysZJSON_SORT_KEYST)	r
   r   
blueprintsget	blueprint
setdefaultZjson_encoderconfigr   )kwargsappbpr   r   r   _dump_arg_defaultso   s    !%r@   c             C   s{   | d k r t  } | rg t r3 | j j t j  n d } |  j d | rZ | j rZ | j n | j  n |  j d t  d S)z,Inject default arguments for load functions.Nr5   )r
   r   r8   r9   r:   r;   Zjson_decoderr   )r=   r>   r?   r   r   r   _load_arg_defaults   s    !(rA   c             C   s,  |  d d  } | d d  t  j k r- d Sd | k r= d S| t  j t  j f k rY d S| d d  t  j t  j f k r d	 St |  d k r | d d  d
 k r d S| d d d  d k r d S| d d  d
 k r d S| d d d  d k r d St |  d k r(| j d  r$d Sd Sd S)ac  Detect which UTF codec was used to encode the given bytes.

    The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
    accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
    or little endian. Some editors or libraries may prepend a BOM.

    :param data: Bytes in unknown UTF encoding.
    :return: UTF encoding name
    N      z	utf-8-sigs    zutf-8zutf-32r   zutf-16s      z	utf-32-bes     z	utf-16-be   z	utf-32-lez	utf-16-le)codecsBOM_UTF8BOM_UTF32_BEBOM_UTF32_LEBOM_UTF16_BEBOM_UTF16_LElen
startswith)dataheadr   r   r   detect_encoding   s*    
"rO   c             K   sb   t  | d | | j d d  } t j |  |  } | d k	 r^ t | t  r^ | j |  } | S)aO  Serialize ``obj`` to a JSON-formatted string. If there is an
    app context pushed, use the current app's configured encoder
    (:attr:`~flask.Flask.json_encoder`), or fall back to the default
    :class:`JSONEncoder`.

    Takes the same arguments as the built-in :func:`json.dumps`, and
    does some extra configuration based on the application. If the
    simplejson package is installed, it is preferred.

    :param obj: Object to serialize to JSON.
    :param app: App instance to use to configure the JSON encoder.
        Uses ``current_app`` if not given, and falls back to the default
        encoder when not in an app context.
    :param kwargs: Extra arguments passed to :func:`json.dumps`.

    .. versionchanged:: 1.0.3

        ``app`` can be passed directly, rather than requiring an app
        context for configuration.
    r>   r   N)r@   popr-   r   r   r	   encode)objr>   r=   r   rvr   r   r   r      s    c             K   sT   t  | d | | j d d  } | d k	 r= t | |  } t j |  | |  d S)z1Like :func:`dumps` but writes into a file object.r>   r   N)r@   rP   r$   r-   r   )rR   r   r>   r=   r   r   r   r   r      s
    c             K   sh   t  | d | t |  t  rX | j d d  } | d k rI t |   } |  j |  }  t j |  |  S)aX  Deserialize an object from a JSON-formatted string ``s``. If
    there is an app context pushed, use the current app's configured
    decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the
    default :class:`JSONDecoder`.

    Takes the same arguments as the built-in :func:`json.loads`, and
    does some extra configuration based on the application. If the
    simplejson package is installed, it is preferred.

    :param s: JSON string to deserialize.
    :param app: App instance to use to configure the JSON decoder.
        Uses ``current_app`` if not given, and falls back to the default
        encoder when not in an app context.
    :param kwargs: Extra arguments passed to :func:`json.dumps`.

    .. versionchanged:: 1.0.3

        ``app`` can be passed directly, rather than requiring an app
        context for configuration.
    r>   r   N)rA   r   r   rP   rO   decoder-   r   )sr>   r=   r   r   r   r   r      s    c             K   sG   t  | d | t s7 t |  | j d d  p1 d  }  t j |  |  S)z0Like :func:`loads` but reads from a file object.r>   r   Nzutf-8)rA   r   r    rP   r-   r   )r   r>   r=   r   r   r   r      s    !c             K   s[   t  |  |  j d d  j d d  j d d  j d d  } t sW | j d	 d
  } | S)a:  Works exactly like :func:`dumps` but is safe for use in ``<script>``
    tags.  It accepts the same arguments and returns a JSON string.  Note that
    this is available in templates through the ``|tojson`` filter which will
    also mark the result as safe.  Due to how this function escapes certain
    characters this is safe even if used outside of ``<script>`` tags.

    The following characters are escaped in strings:

    -   ``<``
    -   ``>``
    -   ``&``
    -   ``'``

    This makes it safe to embed such strings in any place in HTML with the
    notable exception of double quoted attributes.  In that case single
    quote your attributes or HTML escape it in addition.

    .. versionchanged:: 0.10
       This function's return value is now always safe for HTML usage, even
       if outside of script tags or if used in XHTML.  This rule does not
       hold true when using this function in HTML attributes that are double
       quoted.  Always single quote attributes if you use the ``|tojson``
       filter.  Alternatively use ``|tojson|forceescape``.
    <z\u003c>z\u003e&z\u0026'z\u0027z\/r   )r   replace_slash_escape)rR   r=   rS   r   r   r   r     s    c             K   s    | j  t t |  |    d S)z:Like :func:`htmlsafe_dumps` but writes into a file object.N)r"   r	   r   )rR   r   r=   r   r   r   r   -  s    c              O   s   d } d } t  j d s" t  j r. d } d } |  rI | rI t d   n+ t |   d	 k rh |  d
 } n |  pq | } t  j t | d | d | d d t  j d S)a  This function wraps :func:`dumps` to add a few enhancements that make
    life easier.  It turns the JSON output into a :class:`~flask.Response`
    object with the :mimetype:`application/json` mimetype.  For convenience, it
    also converts multiple arguments into an array or multiple keyword arguments
    into a dict.  This means that both ``jsonify(1,2,3)`` and
    ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.

    For clarity, the JSON serialization behavior has the following differences
    from :func:`dumps`:

    1. Single argument: Passed straight through to :func:`dumps`.
    2. Multiple arguments: Converted to an array before being passed to
       :func:`dumps`.
    3. Multiple keyword arguments: Converted to a dict before being passed to
       :func:`dumps`.
    4. Both args and kwargs: Behavior undefined and will throw an exception.

    Example usage::

        from flask import jsonify

        @app.route('/_get_current_user')
        def get_current_user():
            return jsonify(username=g.user.username,
                           email=g.user.email,
                           id=g.user.id)

    This will send a JSON response like this to the browser::

        {
            "username": "admin",
            "email": "admin@localhost",
            "id": 42
        }


    .. versionchanged:: 0.11
       Added support for serializing top-level arrays. This introduces a
       security risk in ancient browsers. See :ref:`json-security` for details.

    This function's response will be pretty printed if the
    ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the
    Flask app is running in debug mode. Compressed (not pretty) formatting
    currently means no indents and no spaces after separators.

    .. versionadded:: 0.2
    N,:ZJSONIFY_PRETTYPRINT_REGULARr   , : z=jsonify() behavior undefined when passed both args and kwargsrD   r   indent
separators
mimetypeZJSONIFY_MIMETYPE)r\   r]   )r^   r_   )r
   r<   debugr#   rK   response_classr   )argsr=   r`   ra   rM   r   r   r   r   2  s    1c             K   s   t  t |  |   S)N)r   r   )rR   r=   r   r   r   tojson_filterw  s    rg   )&r4   rE   r   r(   r   r   Zitsdangerousr   r-   Zjinja2r   Zwerkzeug.httpr   _compatr   r	   globalsr
   r   r+   ImportErrorr   r[   __all__r    r$   r   r   r@   rA   rO   r   r   r   r   r   r   rg   r   r   r   r   <module>   sR   	*+	%E