B
    `l                @   sR  d dl Z d dlZd dlZd dlZd dlZd dlmZmZmZm	Z	 d dl
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	lmZmZmZmZm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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 d dl:Zd dl;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZDmEZEmFZFmGZG d dlHmIZI d dlJZd dlJmKZKmLZLmMZMmNZNmOZOmPZPmQZQ eMZMeNZNeOZOePZPee-G dd dZRdd ZSdeS_Tdd ZUdd ZVdd ZWG d d! d!ZXd"d# ZYd$d% ZZee7G d&d' d'Z[ee4G d(d) d)Z\dS )*    N)quoteurljoinurlparse
urlunparse)Accept)	InterfaceimplementedByimplementer)
IInterface)	renderers)resolve_asset_spec)action_method)DEFAULT_PHASH	MAX_ORDERnormalize_accept_offer
predvalseqsort_accept_offers)reify)ConfigurationErrorPredicateMismatch)HTTPForbiddenHTTPNotFounddefault_exceptionresponse_view)PHASE1_CONFIGIAcceptOrder
IExceptionIExceptionViewClassifier
IMultiViewIPackageOverridesIRendererFactoryIRequest	IResponseIRouteRequestISecuredViewIStaticURLInfoIViewIViewClassifierIViewDeriverInfoIViewDeriversIViewMapperFactory)Deferred)NO_PERMISSION_REQUIRED)static_view)parse_url_overrides)WINTopologicalSorteras_sorted_tupleis_nonstr_iter)AppendSlashNotFoundViewFactory)INGRESSVIEWDefaultViewMapperpreserve_view_attrsrequestonlyview_description
wraps_viewc               @   sN   e Zd Zdd Zdd ZdddZdd	 Zd
d Zdd Zdd Z	dd Z
dS )	MultiViewc             C   s   || _ i | _g | _g | _d S )N)namemedia_viewsviewsaccepts)selfr;    r@   \/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/config/views.py__init__O   s    zMultiView.__init__c             C   s   |  ||}|||S )N)match__discriminator__)r?   contextrequestviewr@   r@   rA   rD   U   s    zMultiView.__discriminator__Nc             C   s  |d k	rFx<t t| jD ]*\}\}}}	||	kr|||f| j|< d S qW |d krv| j|||f | jjtdd n| j|g }
xZt t|
D ](\}\}}}	||	kr|||f|
|< d S qW |
|||f |
jtdd t	| j
}|| |rdd | D }t||| _
d S )Nr   )keyc             S   s   g | ]\}}|qS r@   r@   ).0_vr@   r@   rA   
<listcomp>u   s    z!MultiView.add.<locals>.<listcomp>)	enumeratelistr=   appendsortoperator
itemgetterr<   
setdefaultsetr>   addsortedr   )r?   rG   orderphashacceptaccept_orderisrK   hZsubsetr>   r@   r@   rA   rU   ^   s(    

zMultiView.addc             C   sV   | j rPt|drPg }x*|j| j D ]\}}|| j|  q$W || j |S | jS )NrY   )r>   hasattrrY   Zacceptable_offersextendr<   r=   )r?   rF   r=   ZofferrJ   r@   r@   rA   	get_viewsx   s    zMultiView.get_viewsc             C   sF   x6|  |D ](\}}}t|ds$|S |||r|S qW t| jd S )N__predicated__)r`   r^   ra   r   r;   )r?   rE   rF   rW   rG   rX   r@   r@   rA   rC      s    
zMultiView.matchc             C   s&   |  ||}t|dr"|||S dS )N__permitted__T)rC   r^   rb   )r?   rE   rF   rG   r@   r@   rA   rb      s    
zMultiView.__permitted__c             C   s"   |  ||}t|d|}|||S )N__call_permissive__)rC   getattr)r?   rE   rF   rG   r@   r@   rA   rc      s    zMultiView.__call_permissive__c          	   C   sJ   x:|  |D ],\}}}y
|||S  tk
r6   wY qX qW t| jd S )N)r`   r   r;   )r?   rE   rF   rW   rG   rX   r@   r@   rA   __call__   s    
zMultiView.__call__)NNN)__name__
__module____qualname__rB   rD   rU   r`   rC   rb   rc   re   r@   r@   r@   rA   r:   M   s   	
	r:   c                s   |j dd t|dtt|dt  }}}|d krF|tkrF|tkrF S  fdd}||_||_||_|j d|_|j d|_	|S )NrY   rW   rX   c                s
    | |S )Nr@   )rE   rF   )rG   r@   rA   	attr_view   s    z$attr_wrapped_view.<locals>.attr_viewattr
permission)
optionsgetrd   r   r   
__accept__	__order__	__phash____view_attr____permission__)rG   inforY   rW   rX   ri   r@   )rG   rA   attr_wrapped_view   s    
rt   )rY   rj   rk   c                s8   |j   sS  fdd} fdd}||_ |_|S )Nc                sB   x6 D ].}|| |st d}td|| f qW | |S )Nrf   z#predicate mismatch for view %s (%s))rd   r   text)rE   rF   	predicateZ	view_name)predsrG   r@   rA   predicate_wrapper   s    

z*predicated_view.<locals>.predicate_wrapperc                s   t  fddD S )Nc             3   s   | ]}| V  qd S )Nr@   )rI   rv   )rE   rF   r@   rA   	<genexpr>   s    z3predicated_view.<locals>.checker.<locals>.<genexpr>)all)rE   rF   )rw   )rE   rF   rA   checker   s    z predicated_view.<locals>.checker)
predicatesra   __predicates__)rG   rs   rx   r{   r@   )rw   rG   rA   predicated_view   s    
r~   c                s    fdd}t  |S )zDecorator for add_view-like methods which takes into account
    __view_defaults__ attached to view it is passed.  Not a documented API but
    used by some external systems.c                sj   i }|r|d }n
| d}| |}t|r@t|di  }d|krPd|d< ||  | f||S )Nr   rG   Z__view_defaults__Z_backframes   )rm   maybe_dottedinspectisclassrd   copyupdate)r?   argkwdefaultsrG   )wrappedr@   rA   wrapper   s    




zviewdefaults.<locals>.wrapper)	functoolswraps)r   r   r@   )r   rA   viewdefaults   s    r   c                 s    fdd}|S )Nc                s   xt  D ]}|| } q
W | S )N)reversed)Zview_callable	decorator)
decoratorsr@   rA   	decorated   s    z%combine_decorators.<locals>.decoratedr@   )r   r   r@   )r   rA   combine_decorators   s    r   c               @   s  e Zd Zeed)ddZdd Zd	d
 Zed*ddZdd Z	dd Z
ed+ddZed,ddZdd Zd-ddZdddddddeeddddddddfddZeed.ddZeZeed/ddZeZeed0dd Zed!d" Zed#d$ Zd1d%d&Zd'd( ZdS )2ViewsConfiguratorMixinN r@   Fc                 s  |rt jdtdd d|kr,t jdtdd  dk	rLt rDtdt  |}|	}			trttj n
s|rdd	 ntd
|dk	r|}t	
|std| dkr|trstddkrtt	
s2tt|trRtj|jjd}g }| t||||| |	||t|d
 
fdd}t|trȈrdf }n
}dd|dt
|	||| |||	d | | |ff	dd	} 	
fdd 
fdd	rĈdd| d}	|d< |d || rֈd |dk	r8|jr8d |jkr8d!|jd"d |jd#< |j d$< |d%< | dk	rpd&d'}|d(< |d || j!||d) dS )*a]  Add a :term:`view configuration` to the current
        configuration state.  Arguments to ``add_view`` are broken
        down below into *predicate* arguments and *non-predicate*
        arguments.  Predicate arguments narrow the circumstances in
        which the view callable will be invoked when a request is
        presented to :app:`Pyramid`; non-predicate arguments are
        informational.

        Non-Predicate Arguments

        view

          A :term:`view callable` or a :term:`dotted Python name`
          which refers to a view callable.  This argument is required
          unless a ``renderer`` argument also exists.  If a
          ``renderer`` argument is passed, and a ``view`` argument is
          not provided, the view callable defaults to a callable that
          returns an empty dictionary (see
          :ref:`views_which_use_a_renderer`).

        permission

          A :term:`permission` that the user must possess in order to invoke
          the :term:`view callable`.  See :ref:`view_security_section` for
          more information about view security and permissions.  This is
          often a string like ``view`` or ``edit``.

          If ``permission`` is omitted, a *default* permission may be used
          for this view registration if one was named as the
          :class:`pyramid.config.Configurator` constructor's
          ``default_permission`` argument, or if
          :meth:`pyramid.config.Configurator.set_default_permission` was used
          prior to this view registration.  Pass the value
          :data:`pyramid.security.NO_PERMISSION_REQUIRED` as the permission
          argument to explicitly indicate that the view should always be
          executable by entirely anonymous users, regardless of the default
          permission, bypassing any :term:`authorization policy` that may be
          in effect.

        attr

          This knob is most useful when the view definition is a class.

          The view machinery defaults to using the ``__call__`` method
          of the :term:`view callable` (or the function itself, if the
          view callable is a function) to obtain a response.  The
          ``attr`` value allows you to vary the method attribute used
          to obtain the response.  For example, if your view was a
          class, and the class has a method named ``index`` and you
          wanted to use this method instead of the class' ``__call__``
          method to return the response, you'd say ``attr="index"`` in the
          view configuration for the view.

        renderer

          This is either a single string term (e.g. ``json``) or a
          string implying a path or :term:`asset specification`
          (e.g. ``templates/views.pt``) naming a :term:`renderer`
          implementation.  If the ``renderer`` value does not contain
          a dot ``.``, the specified string will be used to look up a
          renderer implementation, and that renderer implementation
          will be used to construct a response from the view return
          value.  If the ``renderer`` value contains a dot (``.``),
          the specified term will be treated as a path, and the
          filename extension of the last element in the path will be
          used to look up the renderer implementation, which will be
          passed the full path.  The renderer implementation will be
          used to construct a :term:`response` from the view return
          value.

          Note that if the view itself returns a :term:`response` (see
          :ref:`the_response`), the specified renderer implementation
          is never called.

          When the renderer is a path, although a path is usually just
          a simple relative pathname (e.g. ``templates/foo.pt``,
          implying that a template named "foo.pt" is in the
          "templates" directory relative to the directory of the
          current :term:`package` of the Configurator), a path can be
          absolute, starting with a slash on UNIX or a drive letter
          prefix on Windows.  The path can alternately be a
          :term:`asset specification` in the form
          ``some.dotted.package_name:relative/path``, making it
          possible to address template assets which live in a
          separate package.

          The ``renderer`` attribute is optional.  If it is not
          defined, the "null" renderer is assumed (no rendering is
          performed and the value is passed back to the upstream
          :app:`Pyramid` machinery unmodified).

        http_cache

          .. versionadded:: 1.1

          When you supply an ``http_cache`` value to a view configuration,
          the ``Expires`` and ``Cache-Control`` headers of a response
          generated by the associated view callable are modified.  The value
          for ``http_cache`` may be one of the following:

          - A nonzero integer.  If it's a nonzero integer, it's treated as a
            number of seconds.  This number of seconds will be used to
            compute the ``Expires`` header and the ``Cache-Control:
            max-age`` parameter of responses to requests which call this view.
            For example: ``http_cache=3600`` instructs the requesting browser
            to 'cache this response for an hour, please'.

          - A ``datetime.timedelta`` instance.  If it's a
            ``datetime.timedelta`` instance, it will be converted into a
            number of seconds, and that number of seconds will be used to
            compute the ``Expires`` header and the ``Cache-Control:
            max-age`` parameter of responses to requests which call this view.
            For example: ``http_cache=datetime.timedelta(days=1)`` instructs
            the requesting browser to 'cache this response for a day, please'.

          - Zero (``0``).  If the value is zero, the ``Cache-Control`` and
            ``Expires`` headers present in all responses from this view will
            be composed such that client browser cache (and any intermediate
            caches) are instructed to never cache the response.

          - A two-tuple.  If it's a two tuple (e.g. ``http_cache=(1,
            {'public':True})``), the first value in the tuple may be a
            nonzero integer or a ``datetime.timedelta`` instance; in either
            case this value will be used as the number of seconds to cache
            the response.  The second value in the tuple must be a
            dictionary.  The values present in the dictionary will be used as
            input to the ``Cache-Control`` response header.  For example:
            ``http_cache=(3600, {'public':True})`` means 'cache for an hour,
            and add ``public`` to the Cache-Control header of the response'.
            All keys and values supported by the
            ``webob.cachecontrol.CacheControl`` interface may be added to the
            dictionary.  Supplying ``{'public':True}`` is equivalent to
            calling ``response.cache_control.public = True``.

          Providing a non-tuple value as ``http_cache`` is equivalent to
          calling ``response.cache_expires(value)`` within your view's body.

          Providing a two-tuple value as ``http_cache`` is equivalent to
          calling ``response.cache_expires(value[0], **value[1])`` within your
          view's body.

          If you wish to avoid influencing, the ``Expires`` header, and
          instead wish to only influence ``Cache-Control`` headers, pass a
          tuple as ``http_cache`` with the first element of ``None``, e.g.:
          ``(None, {'public':True})``.

          If you wish to prevent a view that uses ``http_cache`` in its
          configuration from having its caching response headers changed by
          this machinery, set ``response.cache_control.prevent_auto = True``
          before returning the response from the view.  This effectively
          disables any HTTP caching done by ``http_cache`` for that response.

        require_csrf

          .. versionadded:: 1.7

          A boolean option or ``None``. Default: ``None``.

          If this option is set to ``True`` then CSRF checks will be enabled
          for requests to this view. The required token or header default to
          ``csrf_token`` and ``X-CSRF-Token``, respectively.

          CSRF checks only affect "unsafe" methods as defined by RFC2616. By
          default, these methods are anything except
          ``GET``, ``HEAD``, ``OPTIONS``, and ``TRACE``.

          The defaults here may be overridden by
          :meth:`pyramid.config.Configurator.set_default_csrf_options`.

          This feature requires a configured :term:`session factory`.

          If this option is set to ``False`` then CSRF checks will be disabled
          regardless of the default ``require_csrf`` setting passed
          to ``set_default_csrf_options``.

          See :ref:`auto_csrf_checking` for more information.

        wrapper

          The :term:`view name` of a different :term:`view
          configuration` which will receive the response body of this
          view as the ``request.wrapped_body`` attribute of its own
          :term:`request`, and the :term:`response` returned by this
          view as the ``request.wrapped_response`` attribute of its
          own request.  Using a wrapper makes it possible to "chain"
          views together to form a composite response.  The response
          of the outermost wrapper view will be returned to the user.
          The wrapper view will be found as any view is found: see
          :ref:`view_lookup`.  The "best" wrapper view will be found
          based on the lookup ordering: "under the hood" this wrapper
          view is looked up via
          ``pyramid.view.render_view_to_response(context, request,
          'wrapper_viewname')``. The context and request of a wrapper
          view is the same context and request of the inner view.  If
          this attribute is unspecified, no view wrapping is done.

        decorator

          A :term:`dotted Python name` to function (or the function itself,
          or an iterable of the aforementioned) which will be used to
          decorate the registered :term:`view callable`.  The decorator
          function(s) will be called with the view callable as a single
          argument.  The view callable it is passed will accept
          ``(context, request)``.  The decorator(s) must return a
          replacement view callable which also accepts ``(context,
          request)``.

          If decorator is an iterable, the callables will be combined and
          used in the order provided as a decorator.
          For example::

            @view_config(...,
                decorator=(decorator2,
                           decorator1))
            def myview(request):
                ....

          Is similar to doing::

            @view_config(...)
            @decorator2
            @decorator1
            def myview(request):
                ...

          Except with the existing benefits of ``decorator=`` (having a common
          decorator syntax for all view calling conventions and not having to
          think about preserving function attributes such as ``__name__`` and
          ``__module__`` within decorator logic).

          An important distinction is that each decorator will receive a
          response object implementing :class:`pyramid.interfaces.IResponse`
          instead of the raw value returned from the view callable. All
          decorators in the chain must return a response object or raise an
          exception:

          .. code-block:: python

             def log_timer(wrapped):
                 def wrapper(context, request):
                     start = time.time()
                     response = wrapped(context, request)
                     duration = time.time() - start
                     response.headers['X-View-Time'] = '%.3f' % (duration,)
                     log.info('view took %.3f seconds', duration)
                     return response
                 return wrapper

          .. versionchanged:: 1.4a4
             Passing an iterable.

        mapper

          A Python object or :term:`dotted Python name` which refers to a
          :term:`view mapper`, or ``None``.  By default it is ``None``, which
          indicates that the view should use the default view mapper.  This
          plug-point is useful for Pyramid extension developers, but it's not
          very useful for 'civilians' who are just developing stock Pyramid
          applications. Pay no attention to the man behind the curtain.

        accept

          A :term:`media type` that will be matched against the ``Accept``
          HTTP request header.  If this value is specified, it must be a
          specific media type such as ``text/html`` or ``text/html;level=1``.
          If the media type is acceptable by the ``Accept`` header of the
          request, or if the ``Accept`` header isn't set at all in the request,
          this predicate will match. If this does not match the ``Accept``
          header of the request, view matching continues.

          If ``accept`` is not specified, the ``HTTP_ACCEPT`` HTTP header is
          not taken into consideration when deciding whether or not to invoke
          the associated view callable.

          The ``accept`` argument is technically not a predicate and does
          not support wrapping with :func:`pyramid.config.not_`.

          See :ref:`accept_content_negotiation` for more information.

          .. versionchanged:: 1.10

              Specifying a media range is deprecated and will be removed in
              :app:`Pyramid` 2.0. Use explicit media types to avoid any
              ambiguities in content negotiation.

          .. versionchanged:: 2.0

              Removed support for media ranges.

        exception_only

          .. versionadded:: 1.8

          When this value is ``True``, the ``context`` argument must be
          a subclass of ``Exception``. This flag indicates that only an
          :term:`exception view` should be created, and that this view should
          not match if the traversal :term:`context` matches the ``context``
          argument. If the ``context`` is a subclass of ``Exception`` and
          this value is ``False`` (the default), then a view will be
          registered to match the traversal :term:`context` as well.

        Predicate Arguments

        name

          The :term:`view name`.  Read :ref:`traversal_chapter` to
          understand the concept of a view name.

        context

          An object or a :term:`dotted Python name` referring to an
          interface or class object that the :term:`context` must be
          an instance of, *or* the :term:`interface` that the
          :term:`context` must provide in order for this view to be
          found and called.  This predicate is true when the
          :term:`context` is an instance of the represented class or
          if the :term:`context` provides the represented interface;
          it is otherwise false.  This argument may also be provided
          to ``add_view`` as ``for_`` (an older, still-supported
          spelling). If the view should *only* match when handling
          exceptions, then set the ``exception_only`` to ``True``.

        route_name

          This value must match the ``name`` of a :term:`route
          configuration` declaration (see :ref:`urldispatch_chapter`)
          that must match before this view will be called.

        request_type

          This value should be an :term:`interface` that the
          :term:`request` must provide in order for this view to be
          found and called.  This value exists only for backwards
          compatibility purposes.

        request_method

          This value can be either a string (such as ``"GET"``, ``"POST"``,
          ``"PUT"``, ``"DELETE"``, ``"HEAD"`` or ``"OPTIONS"``) representing
          an HTTP ``REQUEST_METHOD``, or a tuple containing one or more of
          these strings.  A view declaration with this argument ensures that
          the view will only be called when the ``method`` attribute of the
          request (aka the ``REQUEST_METHOD`` of the WSGI environment) matches
          a supplied value.  Note that use of ``GET`` also implies that the
          view will respond to ``HEAD`` as of Pyramid 1.4.

          .. versionchanged:: 1.2
             The ability to pass a tuple of items as ``request_method``.
             Previous versions allowed only a string.

        request_param

          This value can be any string or any sequence of strings.  A view
          declaration with this argument ensures that the view will only be
          called when the :term:`request` has a key in the ``request.params``
          dictionary (an HTTP ``GET`` or ``POST`` variable) that has a
          name which matches the supplied value (if the value is a string)
          or values (if the value is a tuple).  If any value
          supplied has a ``=`` sign in it,
          e.g. ``request_param="foo=123"``, then the key (``foo``)
          must both exist in the ``request.params`` dictionary, *and*
          the value must match the right hand side of the expression
          (``123``) for the view to "match" the current request.

        match_param

          .. versionadded:: 1.2

          This value can be a string of the format "key=value" or a tuple
          containing one or more of these strings.

          A view declaration with this argument ensures that the view will
          only be called when the :term:`request` has key/value pairs in its
          :term:`matchdict` that equal those supplied in the predicate.
          e.g. ``match_param="action=edit"`` would require the ``action``
          parameter in the :term:`matchdict` match the right hand side of
          the expression (``edit``) for the view to "match" the current
          request.

          If the ``match_param`` is a tuple, every key/value pair must match
          for the predicate to pass.

        containment

          This value should be a Python class or :term:`interface` (or a
          :term:`dotted Python name`) that an object in the
          :term:`lineage` of the context must provide in order for this view
          to be found and called.  The nodes in your object graph must be
          "location-aware" to use this feature.  See
          :ref:`location_aware` for more information about
          location-awareness.

        xhr

          This value should be either ``True`` or ``False``.  If this
          value is specified and is ``True``, the :term:`request`
          must possess an ``HTTP_X_REQUESTED_WITH`` (aka
          ``X-Requested-With``) header that has the value
          ``XMLHttpRequest`` for this view to be found and called.
          This is useful for detecting AJAX requests issued from
          jQuery, Prototype and other Javascript libraries.

        header

          This argument can be a string or an iterable of strings for HTTP
          headers.  The matching is determined as follow:

          - If a string does not contain a ``:`` (colon), it will be
            considered to be a header name (example ``If-Modified-Since``).
            In this case, the header specified by the name must be present
            in the request for this string to match.  Case is not significant.

          - If a string contains a colon, it will be considered a
            name/value pair (for example ``User-Agent:Mozilla/.*`` or
            ``Host:localhost``), where the value part is a regular
            expression.  The header specified by the name must be present
            in the request *and* the regular expression specified as the
            value part must match the value of the request header.  Case is
            not significant for the header name, but it is for the value.

          All strings must be matched for this predicate to return ``True``.
          If this predicate returns ``False``, view matching continues.

        path_info

          This value represents a regular expression pattern that will
          be tested against the ``PATH_INFO`` WSGI environment
          variable.  If the regex matches, this predicate will be
          ``True``.

        physical_path

          If specified, this value should be a string or a tuple representing
          the :term:`physical path` of the context found via traversal for this
          predicate to match as true.  For example: ``physical_path='/'`` or
          ``physical_path='/a/b/c'`` or ``physical_path=('', 'a', 'b', 'c')``.
          This is not a path prefix match or a regex, it's a whole-path match.
          It's useful when you want to always potentially show a view when some
          object is traversed to, but you can't be sure about what kind of
          object it will be, so you can't use the ``context`` predicate.  The
          individual path elements in between slash characters or in tuple
          elements should be the Unicode representation of the name of the
          resource and should not be encoded in any way.

          .. versionadded:: 1.4a3

        is_authenticated

          This value, if specified, must be either ``True`` or ``False``.
          If it is specified and ``True``, only a request from an authenticated
          user, as determined by the :term:`security policy` in use, will
          satisfy the predicate.
          If it is specified and ``False``, only a request from a user who is
          not authenticated will satisfy the predicate.

          .. versionadded:: 2.0

        effective_principals

          If specified, this value should be a :term:`principal` identifier or
          a sequence of principal identifiers.  If the
          :attr:`pyramid.request.Request.effective_principals` property
          indicates that every principal named in the argument list is present
          in the current request, this predicate will return True; otherwise it
          will return False.  For example:
          ``effective_principals=pyramid.authorization.Authenticated`` or
          ``effective_principals=('fred', 'group:admins')``.

          .. versionadded:: 1.4a4

          .. deprecated:: 2.0
              Use ``is_authenticated`` or a custom predicate.

        custom_predicates

            .. deprecated:: 1.5
                This value should be a sequence of references to custom
                predicate callables.  Each custom predicate callable
                should accept two arguments:
                ``context`` and ``request`` and should return either
                ``True`` or ``False`` after doing arbitrary evaluation of
                the context and/or the request.  The ability to register
                custom view predicates via
                :meth:`pyramid.config.Configurator.add_view_predicate`
                obsoletes this argument, but it is kept around for backwards
                compatibility.

        \*\*view_options

          Pass extra keyword parameters to use custom predicates
          or set a value for a view deriver. See
          :meth:`pyramid.config.Configurator.add_view_predicate` and
          :meth:`pyramid.config.Configurator.add_view_deriver`. See
          :ref:`view_and_route_predicates` for more information about
          custom predicates and :ref:`view_derivers` for information
          about view derivers.

          .. versionadded: 1.4a1

          .. versionchanged: 1.7

             Support setting view deriver options. Previously, only custom
             view predicate values could be supplied.

          .. versionchanged:: 2.0

             Removed support for the ``check_csrf`` predicate.

        aJ  The "custom_predicates" argument to Configurator.add_view is deprecated as of Pyramid 1.5. Use "config.add_view_predicate" and use the registered view predicate as a predicate argument to add_view instead. See "Adding A Custom View, Route, or Subscriber Predicate" in the "Hooks" chapter of the documentation for more information.   )
stackleveleffective_principalszThe new security policy has deprecated effective_principals. See "Upgrading Authentication/Authorization" in "What's New in Pyramid 2.0" of the documentation for more information.Nz7A list is not supported in the "accept" view predicate.c             S   s   i S )Nr@   )rE   rF   r@   r@   rA   rG   :  s    z-ViewsConfiguratorMixin.add_view.<locals>.viewz4"view" was not specified and no "renderer" specifiedz)request_type must be an interface, not %szFview "context" must be an exception type when "exception_only" is True)r;   packageregistry)
xhrrequest_method	path_inforequest_paramheaderrY   containmentrequest_typematch_paramcustomc        	         s    d} |  }i }i }x. D ]"\}}||kr>|||< q$|||< q$W jf | | jf|\}}}|||d d |fS )NrG   )rX   rW   r|   )Zget_predlistnamesitems_check_view_optionsmaker   )	ZpredlistZvalid_predicatesZpvalsZdvalskrK   rW   rw   rX   )rE   r;   ovals
route_namer?   	view_intrr@   rA   discrim_funco  s    

z5ViewsConfiguratorMixin.add_view.<locals>.discrim_funczmethod %r of %sr=   rG   )r;   rE   exception_onlyr   r   Zrequest_methodsr   rj   r   rY   r   r   r   
http_cacherequire_csrfcallablemapperr   c                s  t }d k	r0jjtd}|d kr0td |d kr\jtd k	r\tjd jjd}t	|dd }j
}|d k	rd k	r|d k	r|d|d k	rd|j s d|}t|| r d|}t|| r|}srt||}fdd	|_|d
< j  d S )N)r;   z-No route named %s found for view registration)r;   r   r   typezrenderer factoriesFTc                 s    S )Nr@   )r   )discriminatorr@   rA   <lambda>      zCViewsConfiguratorMixin.add_view.<locals>.register.<locals>.<lambda>Zderived_callable)r    r   queryUtilityr"   r   r   r   RendererHelperr   rd   Zintrospectorrm   relater   r&   r   runtime_exc_viewrD   Z_clear_view_lookup_cache)rk   rendererrequest_ifaceZrenderer_typeZintrspcderived_viewZderived_exc_view)	derive_viewr   r   isexcregister_viewr   r?   	tmpl_intrr   r@   rA   register  sD    

	



z1ViewsConfiguratorMixin.add_view.<locals>.registerc                sJ   d }d }d }j 
|| | ||	d}|S )Nr|   rW   rX   )r   rk   r|   rj   rE   r   r   wrapper_viewnameviewnamerY   rW   rX   r   r   r   r   extra_options)_derive_view)Z
isexc_onlyr   rw   rW   rX   r   )rY   rj   rE   r   r   r   r;   r   rk   r   r   r?   rG   r   r   r@   rA   r     s.    z4ViewsConfiguratorMixin.add_view.<locals>.derive_viewc                sP  d }d d  }}j jj}x.tttfD ] }|| |f|}|d k	r,P q,W t|dt}t|}	|	px|d k	ox||k}
|
st	|drt}nt}j 
|| |f| n|	r|}n0t}t|dd }t|dt}||||| j t}|||| | x,ttfD ] }j jj| |f|d qW j j
|| |ftd d S )NrW   rX   rp   rc   rn   ro   )r;   )r   adapters
registeredr%   r#   r   rd   r   
providedByr^   ZregisterAdapterr:   r   rU   r   r   
unregister)
classifierr   r   Zold_viewrW   rX   r   Z	view_typeZ	old_phashZis_multiviewZwant_multiviewZ
view_ifaceZ	multiviewZ
old_acceptZ	old_orderrZ   )rY   rE   r;   	r_contextr?   r   r@   rA   r     sN    


z6ViewsConfiguratorMixin.add_view.<locals>.register_viewzview mapperszview mapper for %szview mapperr   Zroutes.Z	templatestemplater;   r   r   Zpermissionsrk   value)introspectables)"warningswarnDeprecationWarningr1   r   r   r   r   mapr
   r   isexceptionr   r   
isinstancestrr   r   r   r   r   r   dictr   r*   r   r   object_descriptionintrospectablerO   r   r;   r   action) r?   rG   r;   for_rk   r   r   r   r   r   rj   r   r   r   rY   r   r   custom_predicatesrE   r   r   r   r   r   r   view_optionsr   r   Z	view_descr   Zmapper_intrZ	perm_intrr@   )rY   rj   rE   r   r   r   r   r   r   r   r;   r   rk   r   r   r   r   r?   r   rG   r   r   rA   add_view   s        














"A(V





zViewsConfiguratorMixin.add_viewc             K   sV   | j t}x2| D ]&}x t|dg D ]}||d  q(W qW |rRtd|f d S )Nrl   zUnknown view options: %s)r   
getUtilityr(   valuesrd   popr   )r?   r   deriversderiveroptr@   r@   rA   r     s    z*ViewsConfiguratorMixin._check_view_optionsc             C   sR   dt fdtfg}|j}| jt}x*t||  D ]\}}t|||}q4W |S )Nrt   r~   )	rt   r~   original_viewr   r   r(   r   rV   r9   )r?   rs   Zouter_deriversrG   r   r;   r   r@   r@   rA   _apply_view_derivers  s    
z+ViewsConfiguratorMixin._apply_view_deriversc             C   s   | j d||||d dS )a  
        .. versionadded:: 1.4

        Adds a view predicate factory.  The associated view predicate can
        later be named as a keyword argument to
        :meth:`pyramid.config.Configurator.add_view` in the
        ``predicates`` anonyous keyword argument dictionary.

        ``name`` should be the name of the predicate.  It must be a valid
        Python identifier (it will be used as a keyword argument to
        ``add_view`` by others).

        ``factory`` should be a :term:`predicate factory` or :term:`dotted
        Python name` which refers to a predicate factory.

        See :ref:`view_and_route_predicates` for more information.
        rG   )weighs_more_thanweighs_less_thanN)Z_add_predicate)r?   r;   factoryr   r   r@   r@   rA   add_view_predicate  s    z)ViewsConfiguratorMixin.add_view_predicatec             C   s   t j}xd|jfd|jfd|jfd|jfd|jfd|jfd|jfd|j	fd	|j
fd
|jfd|jfd|jfd|jffD ]\}}| || qtW d S )Nr   r   r   r   r   rY   r   r   r   Zphysical_pathis_authenticatedr   r   )pyramidr|   ZXHRPredicateZRequestMethodPredicateZPathInfoPredicateZRequestParamPredicateZHeaderPredicateZAcceptPredicateZContainmentPredicateZRequestTypePredicateZMatchParamPredicateZPhysicalPathPredicateZIsAuthenticatedPredicateZEffectivePrincipalsPredicateZCustomPredicater   )r?   pr;   r   r@   r@   rA   add_default_view_predicates  s     z2ViewsConfiguratorMixin.add_default_view_predicatesc             C   s   xdD ]}|  | qW d S )N)z	text/htmlzapplication/xhtml+xmlzapplication/xmlztext/xmlz
text/plainzapplication/json)add_accept_view_order)r?   rY   r@   r@   rA   add_default_accept_view_order  s    z4ViewsConfiguratorMixin.add_default_accept_view_orderc                s   fdd  fdd}t t\rNtsFg|rhts`g|df}dd}|d< |d< |d< fd	d
}j|||ftd dS )a  
        Specify an ordering preference for the ``accept`` view option used
        during :term:`view lookup`.

        By default, if two views have different ``accept`` options and a
        request specifies ``Accept: */*`` or omits the header entirely then
        it is random which view will be selected. This method provides a way
        to specify a server-side, relative ordering between accept media types.

        ``value`` should be a :term:`media type` as specified by
        :rfc:`7231#section-5.3.2`. For example, ``text/plain;charset=utf8``,
        ``application/json`` or ``text/html``.

        ``weighs_more_than`` and ``weighs_less_than`` control the ordering
        of media types. Each value may be a string or a list of strings. If
        all options for ``weighs_more_than`` (or ``weighs_less_than``) cannot
        be found, it is an error.

        Earlier calls to ``add_accept_view_order`` are given higher priority
        over later calls, assuming similar constraints but standard conflict
        resolution mechanisms can be used to override constraints.

        See :ref:`accept_content_negotiation` for more information.

        .. versionadded:: 1.10

        c                sH   t | \}}}t t|A r(td rD|ks<|krDtdd S )Nz=cannot compare a media type with params to one without paramsz2cannot compare params across different media types)r   parse_offerboolr   )thanZ	than_typeZthan_subtypeZthan_params)offer_paramsoffer_subtype
offer_typer@   rA   
check_type  s    z@ViewsConfiguratorMixin.add_accept_view_order.<locals>.check_typec                s(   dd | D } x| D ]} | qW | S )Nc             S   s   g | ]}t |qS r@   )r   )rI   r   r@   r@   rA   rL     s    zYViewsConfiguratorMixin.add_accept_view_order.<locals>.normalize_types.<locals>.<listcomp>r@   )Zthansr   )r   r@   rA   normalize_types  s    
zEViewsConfiguratorMixin.add_accept_view_order.<locals>.normalize_typeszaccept view orderr   r   r   c                 s>    j t} | d kr(t }  j | t | jd d S )N)beforeafter)r   r   r   r/   registerUtilityrU   )Zsorter)r?   r   r   r   r@   rA   r      s    z>ViewsConfiguratorMixin.add_accept_view_order.<locals>.register)r   rW   N)r   r   r   r1   r   r   r   )r?   r   r   r   r   r   intrr   r@   )r   r   r   r   r?   r   r   r   rA   r     s0     	z,ViewsConfiguratorMixin.add_accept_view_orderc                s     dkr jttfkr0td dkr<ddkrHdtttkrltd tkrdkrtd tkrtd dkrtd	 d
f}dd
}|d<  |d< |d< |d<  fdd}j|||ftd dS )a5  
        .. versionadded:: 1.7

        Add a :term:`view deriver` to the view pipeline. View derivers are
        a feature used by extension authors to wrap views in custom code
        controllable by view-specific options.

        ``deriver`` should be a callable conforming to the
        :class:`pyramid.interfaces.IViewDeriver` interface.

        ``name`` should be the name of the view deriver.  There are no
        restrictions on the name of a view deriver. If left unspecified, the
        name will be constructed from the name of the ``deriver``.

        The ``under`` and ``over`` options can be used to control the ordering
        of view derivers by providing hints about where in the view pipeline
        the deriver is used. Each option may be a string or a list of strings.
        At least one view deriver in each, the over and under directions, must
        exist to fully satisfy the constraints.

        ``under`` means closer to the user-defined :term:`view callable`,
        and ``over`` means closer to view pipeline ingress.

        The default value for ``over`` is ``rendered_view`` and ``under`` is
        ``decorated_view``. This places the deriver somewhere between the two
        in the view pipeline. If the deriver should be placed elsewhere in the
        pipeline, such as above ``decorated_view``, then you MUST also specify
        ``under`` to something earlier in the order, or a
        ``CyclicDependencyError`` will be raised when trying to sort the
        derivers.

        See :ref:`view_derivers` for more information.

        Nz"%s is a reserved view deriver namedecorated_viewrendered_viewz%s cannot be over INGRESSmapped_view)r   z%s cannot be under VIEWz %s cannot be under "mapped_view"zview deriverzview deriversr;   r   underoverc                 sH   j t} | d kr2td tttd} j | t | j d d S )N)Zdefault_beforeZdefault_afterfirstlast)r   r   )r   r   r(   r/   r3   r4   r   rU   )r   )r   r;   r   r?   r   r@   rA   r   z  s    z9ViewsConfiguratorMixin.add_view_deriver.<locals>.register)r   rW   )	r   rf   r3   r4   r   r0   r   r   r   )r?   r   r;   r   r   r   r   r   r@   )r   r;   r   r?   r   rA   add_view_deriver0  s@    $

z'ViewsConfiguratorMixin.add_view_deriverc             C   s~   t j}d|jfd|jfd|jfd|jfd|jfd|jfg}t}x&|D ]\}}| j	|||t
d |}qDW | j	|jdddd	 d S )
Nsecured_viewowrapped_viewhttp_cached_viewr   r   r   )r;   r   r   	csrf_view)r   r   )r   Zviewderiversr  r  r  r   r   r   r3   r  r4   r  )r?   dr   r  r;   r   r@   r@   rA   add_default_view_derivers  s     z0ViewsConfiguratorMixin.add_default_view_deriversc             C   s   | j |||dS )a  
        Create a :term:`view callable` using the function, instance,
        or class (or :term:`dotted Python name` referring to the same)
        provided as ``view`` object.

        .. warning::

           This method is typically only used by :app:`Pyramid` framework
           extension authors, not by :app:`Pyramid` application developers.

        This is API is useful to framework extenders who create
        pluggable systems which need to register 'proxy' view
        callables for functions, instances, or classes which meet the
        requirements of being a :app:`Pyramid` view callable.  For
        example, a ``some_other_framework`` function in another
        framework may want to allow a user to supply a view callable,
        but he may want to wrap the view callable in his own before
        registering the wrapper as a :app:`Pyramid` view callable.
        Because a :app:`Pyramid` view callable can be any of a
        number of valid objects, the framework extender will not know
        how to call the user-supplied object.  Running it through
        ``derive_view`` normalizes it to a callable which accepts two
        arguments: ``context`` and ``request``.

        For example:

        .. code-block:: python

           def some_other_framework(user_supplied_view):
               config = Configurator(reg)
               proxy_view = config.derive_view(user_supplied_view)
               def my_wrapper(context, request):
                   do_something_that_mutates(request)
                   return proxy_view(context, request)
               config.add_view(my_wrapper)

        The ``view`` object provided should be one of the following:

        - A function or another non-class callable object that accepts
          a :term:`request` as a single positional argument and which
          returns a :term:`response` object.

        - A function or other non-class callable object that accepts
          two positional arguments, ``context, request`` and which
          returns a :term:`response` object.

        - A class which accepts a single positional argument in its
          constructor named ``request``, and which has a ``__call__``
          method that accepts no arguments that returns a
          :term:`response` object.

        - A class which accepts two positional arguments named
          ``context, request``, and which has a ``__call__`` method
          that accepts no arguments that returns a :term:`response`
          object.

        - A :term:`dotted Python name` which refers to any of the
          kinds of objects above.

        This API returns a callable which accepts the arguments
        ``context, request`` and which returns the result of calling
        the provided ``view`` object.

        The ``attr`` keyword argument is most useful when the view
        object is a class.  It names the method that should be used as
        the callable.  If ``attr`` is not provided, the attribute
        effectively defaults to ``__call__``.  See
        :ref:`class_as_view` for more information.

        The ``renderer`` keyword argument should be a renderer
        name. If supplied, it will cause the returned callable to use
        a :term:`renderer` to convert the user-supplied view result to
        a :term:`response` object.  If a ``renderer`` argument is not
        supplied, the user-supplied view must itself return a
        :term:`response` object.)rj   r   )r   )r?   rG   rj   r   r@   r@   rA   r     s    Lz"ViewsConfiguratorMixin.derive_viewc             C   s   |  |}|  |}t|tr2tj|| j| jd}|d kr^| jtd k	r^tjd | j| jd}t	|||||||||||||d}|r|
| t|| j| j|||d}|	|_|
|_| |S )N)r;   r   r   )rG   rE   rk   rj   r   r   r;   rY   r   r   r   r   r   )rG   r   r   r|   r   rl   )r   r   r   r   r   r   r   r   r   r   r   ViewDeriverInforW   rX   r   )r?   rG   rk   r|   rj   r   r   r   rY   rW   rX   r   r   r   r   rE   r   r   r   rl   rs   r@   r@   rA   r     sF    



z#ViewsConfiguratorMixin._derive_viewc             K   sx   x"dD ]}||krt d|f qW |dkr0t}t|td|||||	|
||||||||td||d}|| | jf |S )aJ  Add a forbidden view to the current configuration state.  The
        view will be called when Pyramid or application code raises a
        :exc:`pyramid.httpexceptions.HTTPForbidden` exception and the set of
        circumstances implied by the predicates provided are matched.  The
        simplest example is:

          .. code-block:: python

            def forbidden(request):
                return Response('Forbidden', status='403 Forbidden')

            config.add_forbidden_view(forbidden)

        If ``view`` argument is not provided, the view callable defaults to
        :func:`~pyramid.httpexceptions.default_exceptionresponse_view`.

        All arguments have the same meaning as
        :meth:`pyramid.config.Configurator.add_view` and each predicate
        argument restricts the set of circumstances under which this forbidden
        view will be invoked.  Unlike
        :meth:`pyramid.config.Configurator.add_view`, this method will raise
        an exception if passed ``name``, ``permission``, ``require_csrf``,
        ``context``, ``for_``, or ``exception_only`` keyword arguments. These
        argument values make no sense in the context of a forbidden
        :term:`exception view`.

        .. versionadded:: 1.3

        .. versionchanged:: 1.8

           The view is created using ``exception_only=True``.
        )r;   rk   rE   r   r   r   z7%s may not be used as an argument to add_forbidden_viewNTF)rG   rE   r   r   r   r   r   r   r   rY   r   r   r   r   r   r   r   rk   r   rj   r   )r   r   r   r   r+   r   r   )r?   rG   rj   r   r   r   r   r   r   r   r   rY   r   r   r   r   r   r   r   r   settingsr@   r@   rA   add_forbidden_view9  s@    7
z)ViewsConfiguratorMixin.add_forbidden_viewc             K   s   x"dD ]}||krt d|f qW |dkr0t}t|td|||||	|
||||||||tdd}|| |r| j|||d}t|rt	||d}nt	|}||d	< n||d
< ||d< | j
f |S )a  Add a default :term:`Not Found View` to the current configuration
        state. The view will be called when Pyramid or application code raises
        an :exc:`pyramid.httpexceptions.HTTPNotFound` exception (e.g., when a
        view cannot be found for the request).  The simplest example is:

          .. code-block:: python

            def notfound(request):
                return Response('Not Found', status='404 Not Found')

            config.add_notfound_view(notfound)

        If ``view`` argument is not provided, the view callable defaults to
        :func:`~pyramid.httpexceptions.default_exceptionresponse_view`.

        All arguments except ``append_slash`` have the same meaning as
        :meth:`pyramid.config.Configurator.add_view` and each predicate
        argument restricts the set of circumstances under which this notfound
        view will be invoked.  Unlike
        :meth:`pyramid.config.Configurator.add_view`, this method will raise
        an exception if passed ``name``, ``permission``, ``require_csrf``,
        ``context``, ``for_``, or ``exception_only`` keyword arguments. These
        argument values make no sense in the context of a Not Found View.

        If ``append_slash`` is ``True``, when this 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
            config.add_notfound_view(append_slash=HTTPMovedPermanently)

        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.

        :class:`~pyramid.httpexceptions.HTTPTemporaryRedirect` class is used
        as default response, which is equivalent to
        :class:`~pyramid.httpexceptions.HTTPFound` with addition of redirecting
        with the same HTTP method (useful when doing POST requests).

        .. versionadded:: 1.3

        .. versionchanged:: 1.6

           The ``append_slash`` argument was modified to allow any object that
           implements the ``IResponse`` interface to specify the response class
           used when a redirect is performed.

        .. versionchanged:: 1.8

           The view is created using ``exception_only=True``.

        .. versionchanged: 1.10

           Default response was changed from
           :class:`~pyramid.httpexceptions.HTTPFound`
           to :class:`~pyramid.httpexceptions.HTTPTemporaryRedirect`.

        )r;   rk   rE   r   r   r   z6%s may not be used as an argument to add_notfound_viewNTF)rG   rE   r   r   r   r   r   r   r   rY   r   r   r   r   r   r   r   rk   r   )rj   r   )Zredirect_classrG   rj   r   )r   r   r   r   r+   r   r   r!   r   r2   r   )r?   rG   rj   r   r   r   r   r   r   r   r   rY   r   r   r   r   r   r   Zappend_slashr   r   r
  r@   r@   rA   add_notfound_view  sN    b


z(ViewsConfiguratorMixin.add_notfound_viewc          	   K   sT   x"dD ]}||krt d|f qW |dkr0t}|t||dtdd | jf |S )a{  Add an :term:`exception view` for the specified ``exception`` to
        the current configuration state. The view will be called when Pyramid
        or application code raises the given exception.

        This method accepts almost all of the same arguments as
        :meth:`pyramid.config.Configurator.add_view` except for ``name``,
        ``permission``, ``for_``, ``require_csrf``, and ``exception_only``.

        By default, this method will set ``context=Exception``, thus
        registering for most default Python exceptions. Any subclass of
        ``Exception`` may be specified.

        .. versionadded:: 1.8
        )r;   r   r   r   rk   z7%s may not be used as an argument to add_exception_viewNTF)rG   rE   r   rk   r   )r   	Exceptionr   r   r+   r   )r?   rG   rE   r   r   r@   r@   rA   add_exception_view6  s     
z)ViewsConfiguratorMixin.add_exception_viewc                sN       fdd}dt d} |d< jt|t|fd dS )aX  
        Setting a :term:`view mapper` makes it possible to make use of
        :term:`view callable` objects which implement different call
        signatures than the ones supported by :app:`Pyramid` as described in
        its narrative documentation.

        The ``mapper`` argument should be an object implementing
        :class:`pyramid.interfaces.IViewMapperFactory` or a :term:`dotted
        Python name` to such an object.  The provided ``mapper`` will become
        the default view mapper to be used by all subsequent :term:`view
        configuration` registrations.

        .. seealso::

            See also :ref:`using_a_view_mapper`.

        .. note::

           Using the ``default_view_mapper`` argument to the
           :class:`pyramid.config.Configurator` constructor
           can be used to achieve the same purpose.
        c                  s   j  t d S )N)r   r   r)   r@   )r   r?   r@   rA   r     s    z8ViewsConfiguratorMixin.set_view_mapper.<locals>.registerzview mapperszdefault view mapperr   )rW   r   N)r   r   r)   r   r   r   )r?   r   r   r   r@   )r   r?   rA   set_view_mapperf  s    
z&ViewsConfiguratorMixin.set_view_mapperc             K   s(   |  |}|  }|j| ||f| dS )ae  Add a view used to render static assets such as images
        and CSS files.

        The ``name`` argument is a string representing an
        application-relative local URL prefix.  It may alternately be a full
        URL.

        The ``path`` argument is the path on disk where the static files
        reside.  This can be an absolute path, a package-relative path, or a
        :term:`asset specification`.

        The ``cache_max_age`` keyword argument is input to set the
        ``Expires`` and ``Cache-Control`` headers for static assets served.
        Note that this argument has no effect when the ``name`` is a *url
        prefix*.  By default, this argument is ``None``, meaning that no
        particular Expires or Cache-Control headers are set in the response.

        The ``content_encodings`` keyword argument is a list of alternative
        file encodings supported in the ``Accept-Encoding`` HTTP Header.
        Alternative files are found using file extensions defined in
        :attr:`mimetypes.encodings_map`. An encoded asset will be returned
        with the ``Content-Encoding`` header set to the selected encoding.
        If the asset contains alternative encodings then the
        ``Accept-Encoding`` value will be added to the response's ``Vary``
        header. By default, the list is empty and no alternatives will be
        supported.

        The ``permission`` keyword argument is used to specify the
        :term:`permission` required by a user to execute the static view.  By
        default, it is the string
        :data:`pyramid.security.NO_PERMISSION_REQUIRED`, a special sentinel
        which indicates that, even if a :term:`default permission` exists for
        the current application, the static view should be renderered to
        completely anonymous users.  This default value is permissive
        because, in most web apps, static assets seldom need protection from
        viewing.  If ``permission`` is specified, the security checking will
        be performed against the default root factory ACL.

        Any other keyword arguments sent to ``add_static_view`` are passed on
        to :meth:`pyramid.config.Configurator.add_route` (e.g. ``factory``,
        perhaps to define a custom factory with a custom ACL for this static
        view).

        *Usage*

        The ``add_static_view`` function is typically used in conjunction
        with the :meth:`pyramid.request.Request.static_url` method.
        ``add_static_view`` adds a view which renders a static asset when
        some URL is visited; :meth:`pyramid.request.Request.static_url`
        generates a URL to that asset.

        The ``name`` argument to ``add_static_view`` is usually a simple URL
        prefix (e.g. ``'images'``).  When this is the case, the
        :meth:`pyramid.request.Request.static_url` API will generate a URL
        which points to a Pyramid view, which will serve up a set of assets
        that live in the package itself. For example:

        .. code-block:: python

           add_static_view('images', 'mypackage:images/')

        Code that registers such a view can generate URLs to the view via
        :meth:`pyramid.request.Request.static_url`:

        .. code-block:: python

           request.static_url('mypackage:images/logo.png')

        When ``add_static_view`` is called with a ``name`` argument that
        represents a URL prefix, as it is above, subsequent calls to
        :meth:`pyramid.request.Request.static_url` with paths that start with
        the ``path`` argument passed to ``add_static_view`` will generate a
        URL something like ``http://<Pyramid app URL>/images/logo.png``,
        which will cause the ``logo.png`` file in the ``images`` subdirectory
        of the ``mypackage`` package to be served.

        ``add_static_view`` can alternately be used with a ``name`` argument
        which is a *URL*, causing static assets to be served from an external
        webserver.  This happens when the ``name`` argument is a fully
        qualified URL (e.g. starts with ``http://`` or similar).  In this
        mode, the ``name`` is used as the prefix of the full URL when
        generating a URL using :meth:`pyramid.request.Request.static_url`.
        Furthermore, if a protocol-relative URL (e.g. ``//example.com/images``)
        is used as the ``name`` argument, the generated URL will use the
        protocol of the request (http or https, respectively).

        For example, if ``add_static_view`` is called like so:

        .. code-block:: python

           add_static_view('http://example.com/images', 'mypackage:images/')

        Subsequently, the URLs generated by
        :meth:`pyramid.request.Request.static_url` for that static view will
        be prefixed with ``http://example.com/images`` (the external webserver
        listening on ``example.com`` must be itself configured to respond
        properly to such a request.):

        .. code-block:: python

           static_url('mypackage:images/logo.png', request)

        See :ref:`static_assets_section` for more information.

        .. versionchanged:: 2.0

           Added the ``content_encodings`` argument.

        N)
_make_spec_get_static_inforU   )r?   r;   pathr   specrs   r@   r@   rA   add_static_view  s    o
z&ViewsConfiguratorMixin.add_static_viewc             C   s(   |  |}|  }|j| |||d dS )a  
        Add a cache buster to a set of files on disk.

        The ``path`` should be the path on disk where the static files
        reside.  This can be an absolute path, a package-relative path, or a
        :term:`asset specification`.

        The ``cachebust`` argument may be set to cause
        :meth:`~pyramid.request.Request.static_url` to use cache busting when
        generating URLs. See :ref:`cache_busting` for general information
        about cache busting. The value of the ``cachebust`` argument must
        be an object which implements
        :class:`~pyramid.interfaces.ICacheBuster`.

        If ``explicit`` is set to ``True`` then the ``path`` for the cache
        buster will be matched based on the ``rawspec`` instead of the
        ``pathspec`` as defined in the
        :class:`~pyramid.interfaces.ICacheBuster` interface.
        Default: ``False``.

        .. versionadded:: 1.6

        )explicitN)r  r  add_cache_buster)r?   r  	cachebustr  r  rs   r@   r@   rA   r    s    
z'ViewsConfiguratorMixin.add_cache_busterc             C   s,   | j t}|d kr(t }| j |t |S )N)r   r   r$   StaticURLInfor   )r?   rs   r@   r@   rA   r  "  s
    z'ViewsConfiguratorMixin._get_static_info)Nr   NNNNNNNNNNNNNNr@   NNNNNNF)NN)NN)NNN)NN)NNNNNNNNNNNNNr@   NNN)NNNNNNNNNNNNNr@   NNNF)NN)F)rf   rg   rh   r   r   r   r   r   r   r   r   r   r  r  r   r   r   r   r  Zset_forbidden_viewr  Zset_notfound_viewr  r  r  r  r  r@   r@   r@   rA   r      s                                  
Y\
R1                N                   +-s
r   c             C   s6   t | rt| rdS t| tp4t| o4t| tS )NT)	r
   r   r   ZisEqualOrExtendedByr   r  r   r   
issubclass)or@   r@   rA   r   *  s
    


r   c                s    fdd}||_ td|_j|_j|_j|_tdd |_tdt|_tdt	|_
tdd |_tdd |_ fd	d
}|d|_|d|_|d|_|d|_|S )Nc                s    t |dd r | |S | |S )N	exception)rd   )rE   rF   )excviewrG   r@   rA   wrapper_view7  s    
z&runtime_exc_view.<locals>.wrapper_view__original_view__rn   ro   rp   rq   rr   c                s    fdd}|S )Nc                s8   t |dd r}n}t | d }|d k	r4|| |S d S )Nr  )rd   )rE   rF   Zselected_viewfn)rj   r  rG   r@   rA   r   J  s    z2runtime_exc_view.<locals>.wrap_fn.<locals>.wrapperr@   )rj   r   )r  rG   )rj   rA   wrap_fnI  s    	z!runtime_exc_view.<locals>.wrap_fnrc   rb   ra   r}   )Z	__wraps__rd   r  rg   __doc__rf   rn   r   ro   r   rp   rq   rr   rc   rb   ra   r}   )rG   r  r  r   r@   )r  rG   rA   r   3  s"    



r   c               @   s    e Zd Zdd Zedd ZdS )r	  c             C   s0   || _ || _|| _|pg | _|p"i | _|| _d S )N)r   r   r   r|   rl   r   )r?   rG   r   r   r|   r   rl   r@   r@   rA   rB   `  s    

zViewDeriverInfo.__init__c             C   s   | j jS )N)r   r
  )r?   r@   r@   rA   r
  j  s    zViewDeriverInfo.settingsN)rf   rg   rh   rB   r   r
  r@   r@   r@   rA   r	  ^  s   
r	  c               @   s6   e Zd Zdd Zdd Zdd Zddd	Zd
d ZdS )r  c             C   s   g | _ g | _d S )N)registrationscache_busters)r?   r@   r@   rA   rB   q  s    zStaticURLInfo.__init__c             K   s   x| j D ]\}}}||r|t|d  }tr<|dd}| jrV| ||||\}}|d krt||d< |j|f|S t||\}}	}
t	|}|j
st|j|j
d}t|}t||}||	 |
 S qW td| d S )N\/subpath)schemez$No static URL definition matching %s)r"  
startswithlenr.   replacer#  _bust_asset_pathZ	route_urlr-   r   r'  r   _replacer   r   
ValueError)r?   r  rF   r   urlr  r   r&  Zapp_urlqsanchorparsedresultr@   r@   rA   generateu  s(    

zStaticURLInfo.generatec                sl  t jrt j}nd}|s4ds4|  dsF d  t jrZ d nd |dd }|dg }t|d|j	j
d |d}|dd }	|	d krt}	|d	d }
|
d kr|d
d }
|dd }d  }|jrd|j f nd  |j|f| |j||	|
|d  fdd}|d d  d} |d< |d< |jd ||fd d S )Nr%  :cache_max_agecontent_encodingsTzpyramid.reload_assets)r5  Zuse_subpathreloadr6  rk   rE   r   r   z
%s*subpathz__%s/%sz__%s)r   rG   rk   rE   r   c                 sD   j } dd | D } |kr0| }| | | f d S )Nc             S   s   g | ]}|d  qS )r   r@   )rI   tr@   r@   rA   rL     s    z7StaticURLInfo.add.<locals>.register.<locals>.<listcomp>)r"  indexr   rO   )r"  r   idx)r;   r   r?   r  r.  r@   rA   r     s    

z#StaticURLInfo.add.<locals>.registerzstatic viewszstatic view for %rzstatic viewr;   r  )r   r   )osr  isabssependswithr   netlocr   r,   r   r
  r+   Zroute_prefixZ	add_router   r   r   )r?   configr;   r  extrar=  r5  r6  rG   rk   rE   r   patternr   r   r@   )r;   r   r?   r  r.  rA   rU     sV    


zStaticURLInfo.addFc                s   t jrt j}nd}|s4ds4|  fdd}dd d} |d< |d	< |d
< jd ||fd d S )Nr%  r4  c                 s   j jdrd S j} t| d  }}xdt| D ]X\}\}}}|krZ|krZ| }}P q0sj|rj|}P q0|kr0tt|k r0|}P q0W |d k	r| | | | f d S )Nzpyramid.prevent_cachebust)r   r
  rm   r#  r)  rM   r   insert)r#  Znew_idxZold_idxr:  spec_Zcb_Z	explicit_)r  r@  r  r?   r  r@   rA   r     s"    
z0StaticURLInfo.add_cache_buster.<locals>.registerzcache busterszcache buster for %rzcache busterr  r  r  )r   r   )r;  r  r<  r=  r>  r   r   )r?   r@  r  r  r  r=  r   r   r@   )r  r@  r  r?   r  rA   r    s    zStaticURLInfo.add_cache_busterc             C   s  |j }t|\}}d }|d k	rd|||}	|jt|d}
|
d k	rt||}|
|}x>|D ],\}}||}t	|drd|j
|}P q^W n|| }	|d kr|	}|	|d< ||d< xFt| jD ]8\}}}|r||s|s|	|r||||\}}P qW ||fS )Nz{}:{}{})r;   pkg_namez{}:{}pathspecrawspec)r   r   formatr   r   	posixpathjoinZfiltered_sourcesget_pathr^   rE  r   r#  r(  )r?   rF   r  r&  r   r   rE  Zpkg_subpathrG  rF  Z	overridesresource_namesourcessourceZfiltered_pathrD  r  r  r@   r@   rA   r+  	  s2    


zStaticURLInfo._bust_asset_pathN)F)rf   rg   rh   rB   r3  rU   r  r+  r@   r@   r@   rA   r  o  s
   \
1r  )]r   r   rQ   r;  rI  urllib.parser   r   r   r   r   Zwebob.acceptparser   Zzope.interfacer   r   r	   Zzope.interface.interfacesr
   r   r   Zpyramid.assetr   Zpyramid.config.actionsr   Zpyramid.config.predicatesr   r   r   r   r   Zpyramid.decoratorr   Zpyramid.exceptionsr   r   Zpyramid.httpexceptionsr   r   r   Zpyramid.interfacesr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   Zpyramid.predicatesZpyramid.registryr*   Zpyramid.securityr+   Zpyramid.staticr,   Zpyramid.urlr-   Zpyramid.utilr.   r/   r0   r1   Zpyramid.viewr2   Zpyramid.viewderiversr3   r4   r5   r6   r7   r8   r9   r:   rt   rl   r~   r   r   r   r   r   r	  r  r@   r@   r@   rA   <module>   sn   L$
P
              J	+