B
    `K                 @   sB  d dl mZ d dlZd dlZd dlZd dlmZ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mZmZ d d
lmZ d dlmZ d dlmZ d dlmZ dddZd ddZd!ddZ dd Z!e" Z#G dd dZ$e$ Z%e&dej'Z(G dd de$Z)eeG dd dZ*G dd de*Z+e+ Z,dS )"    )partialN)implementer
providedBy)
Components)get_csrf_token)reify)BeforeRender)HTTPBadRequest)IJSONAdapterIRendererFactoryIRendererInfo)caller_package)_get_response_factory)get_current_registry)
hide_attrsc          	   C   sj   y
|j }W n tk
r"   d}Y nX |dkr2t }t| ||d}t|d |j|d|d}W dQ R X |S )aP  Using the renderer ``renderer_name`` (a template
    or a static renderer), render the value (or set of values) present
    in ``value``. Return the result of the renderer's ``__call__``
    method (usually a string or Unicode).

    If the ``renderer_name`` refers to a file on disk, such as when the
    renderer is a template, it's usually best to supply the name as an
    :term:`asset specification`
    (e.g. ``packagename:path/to/template.pt``).

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer path
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If ``package``
    is ``None`` (the default), the package name of the *caller* of
    this function will be used as the package.

    The ``value`` provided will be supplied as the input to the
    renderer.  Usually, for template renderings, this should be a
    dictionary.  For other renderers, this will need to be whatever
    sort of value the renderer expects.

    The 'system' values supplied to the renderer will include a basic set of
    top-level system names, such as ``request``, ``context``,
    ``renderer_name``, and ``view``.  See :ref:`renderer_system_values` for
    the full list.  If :term:`renderer globals` have been specified, these
    will also be used to augment the value.

    Supply a ``request`` parameter in order to provide the renderer
    with the most correct 'system' values (``request`` and ``context``
    in particular).

    N)namepackageregistryresponse)request)r   AttributeErrorr   RendererHelperr   render)renderer_namevaluer   r   r   helperresult r   Y/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/renderers.pyr      s    #

r   c          	   C   sx   y
|j }W n tk
r"   d}Y nX |dkr2t }t| ||d}t|d$ |dk	rZ||_|j|d|d}W dQ R X |S )as  Using the renderer ``renderer_name`` (a template
    or a static renderer), render the value (or set of values) using
    the result of the renderer's ``__call__`` method (usually a string
    or Unicode) as the response body.

    If the renderer name refers to a file on disk (such as when the
    renderer is a template), it's usually best to supply the name as a
    :term:`asset specification`.

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer name
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If you do
    not supply a ``package`` (or ``package`` is ``None``) the package
    name of the *caller* of this function will be used as the package.

    The ``value`` provided will be supplied as the input to the
    renderer.  Usually, for template renderings, this should be a
    dictionary.  For other renderers, this will need to be whatever
    sort of value the renderer expects.

    The 'system' values supplied to the renderer will include a basic set of
    top-level system names, such as ``request``, ``context``,
    ``renderer_name``, and ``view``.  See :ref:`renderer_system_values` for
    the full list.  If :term:`renderer globals` have been specified, these
    will also be used to argument the value.

    Supply a ``request`` parameter in order to provide the renderer
    with the most correct 'system' values (``request`` and ``context``
    in particular). Keep in mind that any changes made to ``request.response``
    prior to calling this function will not be reflected in the resulting
    response object. A new response object will be created for each call
    unless one is passed as the ``response`` argument.

    .. versionchanged:: 1.6
       In previous versions, any changes made to ``request.response`` outside
       of this function call would affect the returned response. This is no
       longer the case. If you wish to send in a pre-initialized response
       then you may pass one in the ``response`` argument.

    N)r   r   r   r   )r   )r   r   r   r   r   r   render_to_response)r   r   r   r   r   r   r   r   r   r   r   r   H   s    -

r   c             C   s"   |dkrt  }t| ||d}|jS )a  Return the renderer object for the renderer ``renderer_name``.

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer name
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If ``package`` is ``None``
    (the default), the package name of the *caller* of this function
    will be used as the package.

    You may directly supply an :term:`application registry` using the
    ``registry`` argument, and it will be used to look up the renderer.
    Otherwise, the current thread-local registry (obtained via
    :func:`~pyramid.threadlocal.get_current_registry`) will be used.
    N)r   r   r   )r   r   renderer)r   r   r   r   r   r   r   get_renderer   s
    r!   c             C   s   dd }|S )Nc             S   sD   t | tst| } |d}|d k	r@|j}|j}||jkr@d|_| S )Nr   z
text/plain)
isinstancestrgetr   content_typedefault_content_type)r   systemr   r   ctr   r   r   _render   s    


z(string_renderer_factory.<locals>._renderr   )infor)   r   r   r   string_renderer_factory   s    r+   c               @   s8   e Zd ZdZejdfddZdd Zdd Zd	d
 Z	dS )JSONa  Renderer that returns a JSON-encoded string.

    Configure a custom JSON renderer using the
    :meth:`~pyramid.config.Configurator.add_renderer` API at application
    startup time:

    .. code-block:: python

       from pyramid.config import Configurator

       config = Configurator()
       config.add_renderer('myjson', JSON(indent=4))

    Once this renderer is registered as above, you can use
    ``myjson`` as the ``renderer=`` parameter to ``@view_config`` or
    :meth:`~pyramid.config.Configurator.add_view`:

    .. code-block:: python

       from pyramid.view import view_config

       @view_config(renderer='myjson')
       def myview(request):
           return {'greeting':'Hello world'}

    Custom objects can be serialized using the renderer by either
    implementing the ``__json__`` magic method, or by registering
    adapters with the renderer.  See
    :ref:`json_serializing_custom_objects` for more information.

    .. note::

        The default serializer uses ``json.JSONEncoder``. A different
        serializer can be specified via the ``serializer`` argument.  Custom
        serializers should accept the object, a callback ``default``, and any
        extra ``kw`` keyword arguments passed during renderer construction.
        This feature isn't widely used but it can be used to replace the
        stock JSON serializer with, say, simplejson.  If all you want to
        do, however, is serialize custom objects, you should use the method
        explained in :ref:`json_serializing_custom_objects` instead
        of replacing the serializer.

    .. versionadded:: 1.4
       Prior to this version, there was no public API for supplying options
       to the underlying serializer without defining a custom renderer.
    r   c             K   s6   || _ || _t | _x|D ]\}}| || qW dS )zLAny keyword arguments will be passed to the ``serializer``
        function.N)
serializerkwr   
componentsadd_adapter)selfr-   adaptersr.   typeadapterr   r   r   __init__   s
    zJSON.__init__c             C   s   | j ||ft dS )a  When an object of the type (or interface) ``type_or_iface`` fails
        to automatically encode using the serializer, the renderer will use
        the adapter ``adapter`` to convert it into a JSON-serializable
        object.  The adapter must accept two arguments: the object and the
        currently active request.

        .. code-block:: python

           class Foo:
               x = 5

           def foo_adapter(obj, request):
               return obj.x

           renderer = JSON(indent=4)
           renderer.add_adapter(Foo, foo_adapter)

        When you've done this, the JSON renderer will be able to serialize
        instances of the ``Foo`` class when they're encountered in your view
        results.N)r/   ZregisterAdapterr
   )r1   Ztype_or_ifacer4   r   r   r   r0      s    zJSON.add_adapterc                s    fdd}|S )zReturns a plain JSON-encoded string with content-type
        ``application/json``. The content-type may be overridden by
        setting ``request.response.content_type``.c                sP   | d}|d k	r.|j}|j}||jkr.d|_ |} j| fd|i jS )Nr   zapplication/jsondefault)r$   r   r%   r&   _make_defaultr-   r.   )r   r'   r   r   r(   r6   )r1   r   r   r)     s    


zJSON.__call__.<locals>._renderr   )r1   r*   r)   r   )r1   r   __call__  s    
zJSON.__call__c                s    fdd}|S )Nc                sV   t | dr|  S t| }jj}|j|fttd}|tkrLtd| f ||  S )N__json__)r6   z%r is not JSON serializable)	hasattrr9   r   r/   r2   lookupr
   _marker	TypeError)objZ	obj_ifacer2   r   )r   r1   r   r   r6     s    

z#JSON._make_default.<locals>.defaultr   )r1   r   r6   r   )r   r1   r   r7     s    zJSON._make_defaultN)
__name__
__module____qualname____doc__jsondumpsr5   r0   r8   r7   r   r   r   r   r,      s
   .	r,   z^[$a-z_][$0-9a-z_\.\[\]]+[^.]$c               @   s"   e Zd ZdZdddZdd ZdS )	JSONPa  `JSONP <https://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper
    which implements a hybrid json/jsonp renderer.  JSONP is useful for
    making cross-domain AJAX requests.

    Configure a JSONP renderer using the
    :meth:`pyramid.config.Configurator.add_renderer` API at application
    startup time:

    .. code-block:: python

       from pyramid.config import Configurator

       config = Configurator()
       config.add_renderer('jsonp', JSONP(param_name='callback'))

    The class' constructor also accepts arbitrary keyword arguments.  All
    keyword arguments except ``param_name`` are passed to the ``json.dumps``
    function as its keyword arguments.

    .. code-block:: python

       from pyramid.config import Configurator

       config = Configurator()
       config.add_renderer('jsonp', JSONP(param_name='callback', indent=4))

    .. versionchanged:: 1.4
       The ability of this class to accept a ``**kw`` in its constructor.

    The arguments passed to this class' constructor mean the same thing as
    the arguments passed to :class:`pyramid.renderers.JSON` (including
    ``serializer`` and ``adapters``).

    Once this renderer is registered via
    :meth:`~pyramid.config.Configurator.add_renderer` as above, you can use
    ``jsonp`` as the ``renderer=`` parameter to ``@view_config`` or
    :meth:`pyramid.config.Configurator.add_view``:

    .. code-block:: python

       from pyramid.view import view_config

       @view_config(renderer='jsonp')
       def myview(request):
           return {'greeting':'Hello world'}

    When a view is called that uses the JSONP renderer:

    - If there is a parameter in the request's HTTP query string that matches
      the ``param_name`` of the registered JSONP renderer (by default,
      ``callback``), the renderer will return a JSONP response.

    - If there is no callback parameter in the request's query string, the
      renderer will return a 'plain' JSON response.

    .. versionadded:: 1.1

    .. seealso::

        See also :ref:`jsonp_renderer`.
    callbackc             K   s   || _ tj| f| d S )N)
param_namer,   r5   )r1   rG   r.   r   r   r   r5   l  s    zJSONP.__init__c                s    fdd}|S )zReturns JSONP-encoded string with content-type
        ``application/javascript`` if query parameter matching
        ``self.param_name`` is present in request.GET; otherwise returns
        plain-JSON encoded string with content-type ``application/json``c       	         s   | d} |} j| fd|i j}d}|}|d k	r|j  j}|d k	rtt|sdtdd}d	||}|j
}|j|jkr||_|S )Nr   r6   zapplication/jsonz%Invalid JSONP callback function name.zapplication/javascriptz/**/{}({});)r$   r7   r-   r.   GETrG   JSONP_VALID_CALLBACKmatchr	   formatr   r%   r&   )	r   r'   r   r6   valr(   bodyrF   r   )r1   r   r   r)   v  s"    


zJSONP.__call__.<locals>._renderr   )r1   r*   r)   r   )r1   r   r8   p  s    zJSONP.__call__N)rF   )r?   r@   rA   rB   r5   r8   r   r   r   r   rE   -  s   =
rE   c               @   sd   e Zd ZdddZedd Zedd Zdd	 Zd
d ZdddZ	dddZ
dd ZdddZdS )r   Nc             C   sP   |rd|krt j|d }n|p$d}|d kr4t }|| _|| _|| _|| _d S )N.    )ospathsplitextr   r   r   r3   r   )r1   r   r   r   Zrtyper   r   r   r5     s    zRendererHelper.__init__c             C   s   | j j}|d kri }|S )N)r   settings)r1   rT   r   r   r   rT     s    zRendererHelper.settingsc             C   s4   | j jt| jd}|d kr,tdt| j || S )N)r   zNo such renderer factory %s)r   ZqueryUtilityr   r3   
ValueErrorr#   )r1   factoryr   r   r   r      s    zRendererHelper.rendererc             C   s   | j S )N)r    )r1   r   r   r   r!     s    zRendererHelper.get_rendererc          	   C   s,   || j | |||tt|d}| j|||dS )N)viewr   renderer_infocontextr   reqr   )r   )r   r   r   r   )r1   r   r   rW   rY   r'   r   r   r   render_view  s    zRendererHelper.render_viewc          	   C   sZ   | j }|d kr2d | j| t|dd ||tt|d}t||}| j}|| |||}|S )NrY   )rW   r   rX   rY   r   rZ   r   )r    r   getattrr   r   r   r   notify)r1   r   system_valuesr   r    r   r   r   r   r   r     s    



zRendererHelper.renderc             C   s   | j |||d}| ||S )N)r   )r   _make_response)r1   r   r^   r   r   r   r   r   r     s    z!RendererHelper.render_to_responsec             C   sr   t |dd }|d kr*| j}t|}||}|d k	rnt|trD||_n*t|trV||_nt|drh||_	n||_|S )Nr   __iter__)
r\   r   r   r"   r#   textbytesrM   r:   Zapp_iter)r1   r   r   r   r   Zresponse_factoryr   r   r   r_     s    


zRendererHelper._make_responsec             C   s:   |d kr| j }|d kr| j}|d kr*| j}| j|||dS )N)r   r   r   )r   r   r   	__class__)r1   r   r   r   r   r   r   clone  s    zRendererHelper.clone)NNN)N)N)NNN)r?   r@   rA   r5   r   rT   r    r!   r[   r   r   r_   rd   r   r   r   r   r     s   


r   c               @   sL   e Zd ZdZdddZedd Zdd Zdd	d
ZdddZ	dddZ
dS )NullRendererHelperaJ  Special renderer helper that has render_* methods which simply return
    the value they are fed rather than converting them to response objects;
    useful for testing purposes and special case view configuration
    registrations that want to use the view configuration machinery but do
    not want actual rendering to happen .Nc             C   s   d | _ d | _d| _d | _d S )NrP   )r   r   r3   r   )r1   r   r   r   r   r   r   r5     s    zNullRendererHelper.__init__c             C   s   i S )Nr   )r1   r   r   r   rT     s    zNullRendererHelper.settingsc             C   s   |S )Nr   )r1   r   r   rW   rY   r   r   r   r[   	  s    zNullRendererHelper.render_viewc             C   s   |S )Nr   )r1   r   r^   r   r   r   r   r     s    zNullRendererHelper.renderc             C   s   |S )Nr   )r1   r   r^   r   r   r   r   r     s    z%NullRendererHelper.render_to_responsec             C   s   | S )Nr   )r1   r   r   r   r   r   r   rd     s    zNullRendererHelper.clone)NNN)N)N)NNN)r?   r@   rA   rB   r5   propertyrT   r[   r   r   rd   r   r   r   r   re     s   
	

re   )NN)NNN)NN)-	functoolsr   rC   rQ   reZzope.interfacer   r   Zzope.interface.registryr   Zpyramid.csrfr   Zpyramid.decoratorr   Zpyramid.eventsr   Zpyramid.httpexceptionsr	   Zpyramid.interfacesr
   r   r   Zpyramid.pathr   Zpyramid.responser   Zpyramid.threadlocalr   Zpyramid.utilr   r   r   r!   r+   objectr<   r,   Zjson_renderer_factorycompileIrI   rE   r   re   Znull_rendererr   r   r   r   <module>   s4   
4
>
tbf!