B
    `t                 @   s<  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mZ d dl	m
Z
mZmZ d dlmZmZmZmZmZmZmZ d dlmZmZ d dlmZmZ e Zd#d
dZd$ddZd%ddZ G dd dZ!e!Z"dd Z#G dd dZ$e$ Z%de%_&G dd dZ'G dd dZ(G dd dZ)d&ddZ*d'dd Z+G d!d" d"Z,dS )(    N)
providedBy)ConfigurationErrorPredicateMismatch)HTTPNotFoundHTTPTemporaryRedirectdefault_exceptionresponse_view)IExceptionViewClassifier
IMultiViewIRequestIRoutesMapperISecuredViewIViewIViewClassifier)get_current_registrymanager)
hide_attrsreraise Tc          	   C   sD   t |dd}|dkrt }t| }t|}t||| ||||d}|S )a  Call the :term:`view callable` configured with a :term:`view
    configuration` that matches the :term:`view name` ``name``
    registered against the specified ``context`` and ``request`` and
    return a :term:`response` object.  This function will return
    ``None`` if a corresponding :term:`view callable` cannot be found
    (when no :term:`view configuration` matches the combination of
    ``name`` / ``context`` / and ``request``).

    If `secure`` is ``True``, and the :term:`view callable` found is
    protected by a permission, the permission will be checked before calling
    the view function.  If the permission check disallows view execution
    (based on the current :term:`authorization policy`), a
    :exc:`pyramid.httpexceptions.HTTPForbidden` exception will be raised.
    The exception's ``args`` attribute explains why the view access was
    disallowed.

    If ``secure`` is ``False``, no permission checking is done.registryN)securerequest_iface)getattrr   r   
_call_view)contextrequestnamer   r   context_ifacer   response r   T/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/view.pyrender_view_to_response   s    r    c             C   s    t | |||}|dkrdS |jS )a#  Call the :term:`view callable` configured with a :term:`view
    configuration` that matches the :term:`view name` ``name``
    registered against the specified ``context`` and ``request`` and
    return an iterable object which represents the body of a response.
    This function will return ``None`` if a corresponding :term:`view
    callable` cannot be found (when no :term:`view configuration`
    matches the combination of ``name`` / ``context`` / and
    ``request``).  Additionally, this function will raise a
    :exc:`ValueError` if a view function is found and called but the
    view function's result does not have an ``app_iter`` attribute.

    You can usually get the bytestring representation of the return value of
    this function by calling ``b''.join(iterable)``, or just use
    :func:`pyramid.view.render_view` instead.

    If ``secure`` is ``True``, and the view is protected by a permission, the
    permission will be checked before the view function is invoked.  If the
    permission check disallows view execution (based on the current
    :term:`security policy`), a
    :exc:`pyramid.httpexceptions.HTTPForbidden` exception will be raised; its
    ``args`` attribute explains why the view access was disallowed.

    If ``secure`` is ``False``, no permission checking is
    done.N)r    Zapp_iter)r   r   r   r   r   r   r   r   render_view_to_iterableO   s    r!   c             C   s$   t | |||}|dkrdS d|S )a  Call the :term:`view callable` configured with a :term:`view
    configuration` that matches the :term:`view name` ``name``
    registered against the specified ``context`` and ``request``
    and unwind the view response's ``app_iter`` (see
    :ref:`the_response`) into a single bytestring.  This function will
    return ``None`` if a corresponding :term:`view callable` cannot be
    found (when no :term:`view configuration` matches the combination
    of ``name`` / ``context`` / and ``request``).  Additionally, this
    function will raise a :exc:`ValueError` if a view function is
    found and called but the view function's result does not have an
    ``app_iter`` attribute. This function will return ``None`` if a
    corresponding view cannot be found.

    If ``secure`` is ``True``, and the view is protected by a permission, the
    permission will be checked before the view is invoked.  If the permission
    check disallows view execution (based on the current :term:`authorization
    policy`), a :exc:`pyramid.httpexceptions.HTTPForbidden` exception will be
    raised; its ``args`` attribute explains why the view access was
    disallowed.

    If ``secure`` is ``False``, no permission checking is done.N    )r!   join)r   r   r   r   iterabler   r   r   render_viewn   s    r%   c               @   s,   e Zd ZdZeZdd Zdd Zdd ZdS )	view_configaE  A function, class or method :term:`decorator` which allows a
    developer to create view registrations nearer to a :term:`view
    callable` definition than use :term:`imperative
    configuration` to do the same.

    For example, this code in a module ``views.py``::

      from resources import MyResource

      @view_config(name='my_view', context=MyResource, permission='read',
                   route_name='site1')
      def my_view(context, request):
          return 'OK'

    Might replace the following call to the
    :meth:`pyramid.config.Configurator.add_view` method::

       import views
       from resources import MyResource
       config.add_view(views.my_view, context=MyResource, name='my_view',
                       permission='read', route_name='site1')

    .. note: :class:`pyramid.view.view_config` is also importable, for
             backwards compatibility purposes, as the name
             :class:`pyramid.view.bfg_view`.

    :class:`pyramid.view.view_config` supports the following keyword
    arguments: ``context``, ``exception``, ``permission``, ``name``,
    ``request_type``, ``route_name``, ``request_method``, ``request_param``,
    ``containment``, ``xhr``, ``accept``, ``header``, ``path_info``,
    ``custom_predicates``, ``decorator``, ``mapper``, ``http_cache``,
    ``require_csrf``, ``match_param``, ``physical_path``, and
    ``view_options``.

    The meanings of these arguments are the same as the arguments passed to
    :meth:`pyramid.config.Configurator.add_view`.  If any argument is left
    out, its default will be the equivalent ``add_view`` default.

    Two additional keyword arguments which will be passed to the
    :term:`venusian` ``attach`` function are ``_depth`` and ``_category``.

    ``_depth`` is provided for people who wish to reuse this class from another
    decorator. The default value is ``0`` and should be specified relative to
    the ``view_config`` invocation. It will be passed in to the
    :term:`venusian` ``attach`` function as the depth of the callstack when
    Venusian checks if the decorator is being used in a class or module
    context. It's not often used, but it can be useful in this circumstance.

    ``_category`` sets the decorator category name. It can be useful in
    combination with the ``category`` argument of ``scan`` to control which
    views should be processed.

    See the :py:func:`venusian.attach` function in Venusian for more
    information about the ``_depth`` and ``_category`` arguments.

    .. seealso::

        See also :ref:`mapping_views_using_a_decorator_section` for
        details about using :class:`pyramid.view.view_config`.

    .. note::

        Because of a limitation with ``venusian.Scanner.scan``, note that
        ``view_config`` will work only for the following conditions.

        -   In Python packages that have an ``__init__.py`` file in their
            directory.

            .. seealso::

                See also https://github.com/Pylons/venusian/issues/68

        -   On module top level members.
        -   On Python source (``.py``) files.
            Compiled Python files (``.pyc``, ``.pyo``) without a corresponding
            source file are ignored.

        .. seealso::

            See also the `Venusian documentation
            <https://docs.pylonsproject.org/projects/venusian/en/latest/#using-venusian>`_.
    c             K   s:   d|kr"| dd kr"|d |d< | j| |   d S )NZfor_r   )get__dict__update	_get_info)selfsettingsr   r   r   __init__   s
    zview_config.__init__c             C   sT   | j dd}t|d }t|}|d d  }|d |d |d |f| _d S )N_depthr            )r(   r'   sys	_getframeinspectgetframeinfostrip_info)r+   depthframe	frameinfoZ
sourceliner   r   r   r*      s
    
zview_config._get_infoc                sn   | j  dd}dd} fdd}| jj||||d d  jd	krjd
d krj|jd
< |S )Nr.   r   	_categorypyramidc                s&   | j  j}|jf d|i d S )Nview)configwith_packagemoduleZadd_view)r   r   obr>   )infor,   r   r   callback   s    z&view_config.__call__.<locals>.callbackr1   )categoryr8   classattr)r(   copypopvenusianattachscoper'   __name__)r+   wrappedr8   rD   rC   r   )rB   r,   r   __call__   s    


zview_config.__call__N)rL   
__module____qualname____doc__rI   r-   r*   rN   r   r   r   r   r&      s
   Rr&   c                 s    fdd}|S )a;  A class :term:`decorator` which, when applied to a class, will
    provide defaults for all view configurations that use the class.  This
    decorator accepts all the arguments accepted by
    :meth:`pyramid.view.view_config`, and each has the same meaning.

    See :ref:`view_defaults` for more information.
    c                s
    | _ | S )N)Z__view_defaults__)rM   )r,   r   r   wrap  s    zview_defaults.<locals>.wrapr   )r,   rR   r   )r,   r   view_defaults  s    	rS   c               @   s&   e Zd ZdZdefddZdd ZdS )AppendSlashNotFoundViewFactorya  There can only be one :term:`Not Found view` in any
    :app:`Pyramid` application.  Even if you use
    :func:`pyramid.view.append_slash_notfound_view` as the Not
    Found view, :app:`Pyramid` still must generate a ``404 Not
    Found`` response when it cannot redirect to a slash-appended URL;
    this not found response will be visible to site users.

    If you don't care what this 404 response looks like, and you only
    need redirections to slash-appended route URLs, you may use the
    :func:`pyramid.view.append_slash_notfound_view` object as the
    Not Found view.  However, if you wish to use a *custom* notfound
    view callable when a URL cannot be redirected to a slash-appended
    URL, you may wish to use an instance of this class as the Not
    Found view, supplying a :term:`view callable` to be used as the
    custom notfound view as the first argument to its constructor.
    For instance:

    .. code-block:: python

       from pyramid.httpexceptions import HTTPNotFound
       from pyramid.view import AppendSlashNotFoundViewFactory

       def notfound_view(context, request): return HTTPNotFound('nope')

       custom_append_slash = AppendSlashNotFoundViewFactory(notfound_view)
       config.add_view(custom_append_slash, context=HTTPNotFound)

    The ``notfound_view`` supplied must adhere to the two-argument
    view callable calling convention of ``(context, request)``
    (``context`` will be the exception object).

    .. deprecated:: 1.3

    Nc             C   s   |d krt }|| _|| _d S )N)r   notfound_viewredirect_class)r+   rU   rV   r   r   r   r-   <  s    z'AppendSlashNotFoundViewFactory.__init__c       	      C   s   |j }|j}|t}|d k	rx|dsx|d }xF| D ]:}||d k	r:|j}|r^d| }| j|j	d | dS q:W | 
||S )N/?)location)Z	path_infor   ZqueryUtilityr   endswithZ
get_routesmatchZquery_stringrV   pathrU   )	r+   r   r   r\   r   ZmapperZ	slashpathZrouteqsr   r   r   rN   D  s    
z'AppendSlashNotFoundViewFactory.__call__)rL   rO   rP   rQ   r   r-   rN   r   r   r   r   rT     s   "rT   a  For behavior like Django's ``APPEND_SLASH=True``, use this view as the
:term:`Not Found view` in your application.

When this view is the Not Found view (indicating that no view was found), and
any routes have been defined in the configuration of your application, if the
value of the ``PATH_INFO`` WSGI environment variable does not already end in
a slash, and if the value of ``PATH_INFO`` *plus* a slash matches any route's
path, do an HTTP redirect to the slash-appended PATH_INFO.  Note that this
will *lose* ``POST`` data information (turning it into a GET), so you
shouldn't rely on this to redirect POST requests.  Note also that static
routes are not considered when attempting to find a matching route.

Use the :meth:`pyramid.config.Configurator.add_view` method to configure this
view as the Not Found view::

  from pyramid.httpexceptions import HTTPNotFound
  from pyramid.view import append_slash_notfound_view
  config.add_view(append_slash_notfound_view, context=HTTPNotFound)

.. deprecated:: 1.3

c               @   s$   e Zd ZdZeZdd Zdd ZdS )notfound_view_configaD
  
    .. versionadded:: 1.3

    An analogue of :class:`pyramid.view.view_config` which registers a
    :term:`Not Found View` using
    :meth:`pyramid.config.Configurator.add_notfound_view`.

    The ``notfound_view_config`` constructor accepts most of the same arguments
    as the constructor of :class:`pyramid.view.view_config`.  It can be used
    in the same places, and behaves in largely the same way, except it always
    registers a not found exception view instead of a 'normal' view.

    Example:

    .. code-block:: python

        from pyramid.view import notfound_view_config
        from pyramid.response import Response

        @notfound_view_config()
        def notfound(request):
            return Response('Not found!', status='404 Not Found')

    All arguments except ``append_slash`` have the same meaning as
    :meth:`pyramid.view.view_config` and each predicate
    argument restricts the set of circumstances under which this notfound
    view will be invoked.

    If ``append_slash`` is ``True``, when the Not Found View is invoked, and
    the current path info does not end in a slash, the notfound logic will
    attempt to find a :term:`route` that matches the request's path info
    suffixed with a slash.  If such a route exists, Pyramid will issue a
    redirect to the URL implied by the route; if it does not, Pyramid will
    return the result of the view callable provided as ``view``, as normal.

    If the argument provided as ``append_slash`` is not a boolean but
    instead implements :class:`~pyramid.interfaces.IResponse`, the
    append_slash logic will behave as if ``append_slash=True`` was passed,
    but the provided class will be used as the response class instead of
    the default :class:`~pyramid.httpexceptions.HTTPTemporaryRedirect`
    response class when a redirect is performed.  For example:

      .. code-block:: python

        from pyramid.httpexceptions import (
            HTTPMovedPermanently,
            HTTPNotFound
            )

        @notfound_view_config(append_slash=HTTPMovedPermanently)
        def aview(request):
            return HTTPNotFound('not found')

    The above means that a redirect to a slash-appended route will be
    attempted, but instead of
    :class:`~pyramid.httpexceptions.HTTPTemporaryRedirect`
    being used, :class:`~pyramid.httpexceptions.HTTPMovedPermanently will
    be used` for the redirect response if a slash-appended route is found.

    See :ref:`changing_the_notfound_view` for detailed usage information.

    .. versionchanged:: 1.9.1
       Added the ``_depth`` and ``_category`` arguments.

    c             K   s   | j | d S )N)r(   r)   )r+   r,   r   r   r   r-     s    znotfound_view_config.__init__c                sx   | j  dd}dd} fdd}| jj||||d d  jd	krjd
d krj|jd
<  jd< |S )Nr.   r   r;   r<   c                s&   | j  j}|jf d|i d S )Nr=   )r>   r?   r@   Zadd_notfound_view)r   r   rA   r>   )rB   r,   r   r   rC     s    z/notfound_view_config.__call__.<locals>.callbackr1   )rD   r8   rE   rF   r7   )	r(   rG   rH   rI   rJ   rK   r'   rL   codeinfo)r+   rM   r8   rD   rC   r   )rB   r,   r   rN     s    



znotfound_view_config.__call__N)rL   rO   rP   rQ   rI   r-   rN   r   r   r   r   r^   o  s   Ar^   c               @   s$   e Zd ZdZeZdd Zdd ZdS )forbidden_view_configa  
    .. versionadded:: 1.3

    An analogue of :class:`pyramid.view.view_config` which registers a
    :term:`forbidden view` using
    :meth:`pyramid.config.Configurator.add_forbidden_view`.

    The forbidden_view_config constructor accepts most of the same arguments
    as the constructor of :class:`pyramid.view.view_config`.  It can be used
    in the same places, and behaves in largely the same way, except it always
    registers a forbidden exception view instead of a 'normal' view.

    Example:

    .. code-block:: python

        from pyramid.view import forbidden_view_config
        from pyramid.response import Response

        @forbidden_view_config()
        def forbidden(request):
            return Response('You are not allowed', status='403 Forbidden')

    All arguments passed to this function have the same meaning as
    :meth:`pyramid.view.view_config` and each predicate argument restricts
    the set of circumstances under which this notfound view will be invoked.

    See :ref:`changing_the_forbidden_view` for detailed usage information.

    .. versionchanged:: 1.9.1
       Added the ``_depth`` and ``_category`` arguments.

    c             K   s   | j | d S )N)r(   r)   )r+   r,   r   r   r   r-     s    zforbidden_view_config.__init__c                sx   | j  dd}dd} fdd}| jj||||d d  jd	krjd
d krj|jd
<  jd< |S )Nr.   r   r;   r<   c                s&   | j  j}|jf d|i d S )Nr=   )r>   r?   r@   Zadd_forbidden_view)r   r   rA   r>   )rB   r,   r   r   rC     s    z0forbidden_view_config.__call__.<locals>.callbackr1   )rD   r8   rE   rF   r7   )	r(   rG   rH   rI   rJ   rK   r'   rL   r_   )r+   rM   r8   rD   rC   r   )rB   r,   r   rN     s    



zforbidden_view_config.__call__N)rL   rO   rP   rQ   rI   r-   rN   r   r   r   r   r`     s   !r`   c               @   s$   e Zd ZdZeZdd Zdd ZdS )exception_view_configa  
    .. versionadded:: 1.8

    An analogue of :class:`pyramid.view.view_config` which registers an
    :term:`exception view` using
    :meth:`pyramid.config.Configurator.add_exception_view`.

    The ``exception_view_config`` constructor requires an exception context,
    and additionally accepts most of the same arguments as the constructor of
    :class:`pyramid.view.view_config`.  It can be used in the same places,
    and behaves in largely the same way, except it always registers an
    exception view instead of a "normal" view that dispatches on the request
    :term:`context`.

    Example:

    .. code-block:: python

        from pyramid.view import exception_view_config
        from pyramid.response import Response

        @exception_view_config(ValueError, renderer='json')
        def error_view(request):
            return {'error': str(request.exception)}

    All arguments passed to this function have the same meaning as
    :meth:`pyramid.view.view_config`, and each predicate argument restricts
    the set of circumstances under which this exception view will be invoked.

    .. versionchanged:: 1.9.1
       Added the ``_depth`` and ``_category`` arguments.

    c             O   sV   d|kr2t |dkr2|d |dd   }}||d< t |dkrFtd| j| d S )Nr   r   r1   zunknown positional arguments)lenr   r(   r)   )r+   argsr,   	exceptionr   r   r   r-   4  s    zexception_view_config.__init__c                sx   | j  dd}dd} fdd}| jj||||d d  jd	krjd
d krj|jd
<  jd< |S )Nr.   r   r;   r<   c                s&   | j  j}|jf d|i d S )Nr=   )r>   r?   r@   Zadd_exception_view)r   r   rA   r>   )rB   r,   r   r   rC   A  s    z0exception_view_config.__call__.<locals>.callbackr1   )rD   r8   rE   rF   r7   )	r(   rG   rH   rI   rJ   rK   r'   rL   r_   )r+   rM   r8   rD   rC   r   )rB   r,   r   rN   <  s    



zexception_view_config.__call__N)rL   rO   rP   rQ   rI   r-   rN   r   r   r   r   ra     s   !ra   c          	   C   s   |d krt ttf}|d krt}| jj}| j}||||f}|d krg }xTt	|j
|j
D ]@\}	}
||	|
f}x,|D ]$}||||d}|d k	rr|| qrW qZW |r| j |||||f< W d Q R X |S )N)r   )r   r   r	   r   adapters
registeredZ_view_lookup_cacher'   	itertoolsproductZ__sro__append_lock)r   r   r   	view_name
view_typesview_classifierrf   cacheZviewsZreq_typeZctx_typeZsource_ifacesZ	view_typeview_callabler   r   r   _find_viewsT  s*    


rp   c	             C   s   |d krt |dt}t| |||||d}	d }
d }xR|	D ]J}y|sLt |d|}|||}|S  tk
r~ } z|}
W d d }~X Y q6X q6W |
d k	r|
|S )Nr   )rl   rm   Z__call_permissive__)r   r
   rp   r   )r   r   r   r   rk   rl   rm   r   r   Zview_callablesZpmer   ro   Z_pmer   r   r   r   |  s.    


r   c               @   s   e Zd ZdZdddZdS )ViewMethodsMixinzKRequest methods mixin for BaseRequest having to do with executing
    viewsNTFc             C   s&  |dkr| }t |dd}|dkr&t }|dkr6td|dkrFt }|d }|j}t|}t|ddd ||d< ||d< |dt	}	t
||d	 zHy t||||d
dt||	jd	}
W n" tk
r   |rt|   Y nX W dt
  X W dQ R X |
dkr|rt|  t||d< ||d< |
S )a  Executes an exception view related to the request it's called upon.
        The arguments it takes are these:

        ``exc_info``

            If provided, should be a 3-tuple in the form provided by
            ``sys.exc_info()``.  If not provided,
            ``sys.exc_info()`` will be called to obtain the current
            interpreter exception information.  Default: ``None``.

        ``request``

            If the request to be used is not the same one as the instance that
            this method is called upon, it may be passed here.  Default:
            ``None``.

        ``secure``

            If the exception view should not be rendered if the current user
            does not have the appropriate permission, this should be ``True``.
            Default: ``True``.

        ``reraise``

            A boolean indicating whether the original error should be reraised
            if a :term:`response` object could not be created. If ``False``
            then an :class:`pyramid.httpexceptions.HTTPNotFound`` exception
            will be raised. Default: ``False``.

        If a response is generated then ``request.exception`` and
        ``request.exc_info`` will be left at the values used to render the
        response. Otherwise the previous values for ``request.exception`` and
        ``request.exc_info`` will be restored.

        .. versionadded:: 1.7

        .. versionchanged:: 1.9
           The ``request.exception`` and ``request.exc_info`` properties will
           reflect the exception used to render the response where previously
           they were reset to the values prior to invoking the method.

           Also added the ``reraise`` argument.

        Nr   zUnable to retrieve registryr1   r   exc_inford   r   )r   r   r   )rl   rm   r   r   )r   r   RuntimeErrorr2   rr   r(   r   r   r'   r
   r   pushr   r   Zcombined	Exceptionreraise_rH   r   )r+   rr   r   r   r   r   excattrsr   r   r   r   r   r   invoke_exception_view  sP    /
z&ViewMethodsMixin.invoke_exception_view)NNTF)rL   rO   rP   rQ   ry   r   r   r   r   rq     s   rq   )r   T)r   T)r   T)NN)NNTN)-r4   rg   r2   rI   Zzope.interfacer   Zpyramid.exceptionsr   r   Zpyramid.httpexceptionsr   r   r   Zpyramid.interfacesr   r	   r
   r   r   r   r   Zpyramid.threadlocalr   r   Zpyramid.utilr   r   rv   objectZ_markerr    r!   r%   r&   Zbfg_viewrS   rT   Zappend_slash_notfound_viewrQ   r^   r`   ra   rp   r   rq   r   r   r   r   <module>   s:   $	
3

{=`@J 
(   
(