Michael Merickel
2018-10-10 4cc3a67060f22bb11d037bd44a24112efca6d507
commit | author | age
8a1b50 1 .. _view_config_chapter:
CD 2
3 .. _view_configuration:
4
e81ad8 5 .. _view_lookup:
CM 6
8a1b50 7 View Configuration
CD 8 ==================
9
10 .. index::
11    single: view lookup
12
803817 13 :term:`View lookup` is the :app:`Pyramid` subsystem responsible for finding and
SP 14 invoking a :term:`view callable`.  :term:`View configuration` controls how
e81ad8 15 :term:`view lookup` operates in your application.  During any given request,
CM 16 view configuration information is compared against request data by the view
17 lookup subsystem in order to find the "best" view callable for that request.
8a1b50 18
e81ad8 19 In earlier chapters, you have been exposed to a few simple view configuration
CM 20 declarations without much explanation. In this chapter we will explore the
21 subject in detail.
8a1b50 22
6ce1e0 23 .. index::
CM 24    pair: resource; mapping to view callable
25    pair: URL pattern; mapping to view callable
26
8a1b50 27 Mapping a Resource or URL Pattern to a View Callable
CD 28 ----------------------------------------------------
29
30 A developer makes a :term:`view callable` available for use within a
31 :app:`Pyramid` application via :term:`view configuration`.  A view
32 configuration associates a view callable with a set of statements that
803817 33 determine the set of circumstances which must be true for the view callable to
SP 34 be invoked.
8a1b50 35
CD 36 A view configuration statement is made about information present in the
e8c66a 37 :term:`context` resource (or exception) and the :term:`request`.
8a1b50 38
026da8 39 View configuration is performed in one of two ways:
8a1b50 40
03e38b 41 - By running a :term:`scan` against application source code which has a
8a1b50 42   :class:`pyramid.view.view_config` decorator attached to a Python object as
70acd2 43   per :ref:`mapping_views_using_a_decorator_section`.
8a1b50 44
03e38b 45 - By using the :meth:`pyramid.config.Configurator.add_view` method as per
8a1b50 46   :ref:`mapping_views_using_imperative_config_section`.
6ce1e0 47
CM 48 .. index::
49    single: view configuration parameters
8a1b50 50
CD 51 .. _view_configuration_parameters:
52
53 View Configuration Parameters
54 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
55
56 All forms of view configuration accept the same general types of arguments.
57
58 Many arguments supplied during view configuration are :term:`view predicate`
803817 59 arguments.  View predicate arguments used during view configuration are used to
SP 60 narrow the set of circumstances in which :term:`view lookup` will find a
2e3f70 61 particular view callable.
8a1b50 62
e81ad8 63 :term:`View predicate` attributes are an important part of view configuration
CM 64 that enables the :term:`view lookup` subsystem to find and invoke the
803817 65 appropriate view.  The greater the number of predicate attributes possessed by
SP 66 a view's configuration, the more specific the circumstances need to be before
67 the registered view callable will be invoked.  The fewer the number of
68 predicates which are supplied to a particular view configuration, the more
69 likely it is that the associated view callable will be invoked.  A view with
70 five predicates will always be found and evaluated before a view with two, for
1fbbb4 71 example.
8a1b50 72
803817 73 This does not mean however, that :app:`Pyramid` "stops looking" when it finds a
SP 74 view registration with predicates that don't match.  If one set of view
75 predicates does not match, the "next most specific" view (if any) is consulted
76 for predicates, and so on, until a view is found, or no view can be matched up
77 with the request.  The first view with a set of predicates all of which match
78 the request environment will be invoked.
8a1b50 79
CD 80 If no view can be found with predicates which allow it to be matched up with
81 the request, :app:`Pyramid` will return an error to the user's browser,
82 representing a "not found" (404) page.  See :ref:`changing_the_notfound_view`
cec2b0 83 for more information about changing the default :term:`Not Found View`.
8a1b50 84
803817 85 Other view configuration arguments are non-predicate arguments.  These tend to
SP 86 modify the response of the view callable or prevent the view callable from
8a1b50 87 being invoked due to an authorization policy.  The presence of non-predicate
CD 88 arguments in a view configuration does not narrow the circumstances in which
89 the view callable will be invoked.
90
e573d4 91 .. _nonpredicate_view_args:
CM 92
8a1b50 93 Non-Predicate Arguments
CD 94 +++++++++++++++++++++++
95
96 ``permission``
97   The name of a :term:`permission` that the user must possess in order to
803817 98   invoke the :term:`view callable`.  See :ref:`view_security_section` for more
SP 99   information about view security and permissions.
2e3f70 100
803817 101   If ``permission`` is not supplied, no permission is registered for this view
SP 102   (it's accessible by any caller).
8a1b50 103
CD 104 ``attr``
105   The view machinery defaults to using the ``__call__`` method of the
106   :term:`view callable` (or the function itself, if the view callable is a
107   function) to obtain a response.  The ``attr`` value allows you to vary the
803817 108   method attribute used to obtain the response.  For example, if your view was
SP 109   a class, and the class has a method named ``index`` and you wanted to use
110   this method instead of the class's ``__call__`` method to return the
111   response, you'd say ``attr="index"`` in the view configuration for the view.
112   This is most useful when the view definition is a class.
8a1b50 113
CD 114   If ``attr`` is not supplied, ``None`` is used (implying the function itself
803817 115   if the view is a function, or the ``__call__`` callable attribute if the view
SP 116   is a class).
8a1b50 117
CD 118 ``renderer``
803817 119   Denotes the :term:`renderer` implementation which will be used to construct a
SP 120   :term:`response` from the associated view callable's return value.
1395f5 121
2033ee 122   .. seealso:: See also :ref:`renderers_chapter`.
8a1b50 123
803817 124   This is either a single string term (e.g., ``json``) or a string implying a
SP 125   path or :term:`asset specification` (e.g., ``templates/views.pt``) naming a
126   :term:`renderer` implementation.  If the ``renderer`` value does not contain
127   a dot (``.``), the specified string will be used to look up a renderer
128   implementation, and that renderer implementation will be used to construct a
129   response from the view return value.  If the ``renderer`` value contains a
130   dot (``.``), the specified term will be treated as a path, and the filename
131   extension of the last element in the path will be used to look up the
132   renderer implementation, which will be passed the full path.
8a1b50 133
803817 134   When the renderer is a path—although a path is usually just a simple relative
SP 135   pathname (e.g., ``templates/foo.pt``, implying that a template named "foo.pt"
136   is in the "templates" directory relative to the directory of the current
5af300 137   :term:`package`)—the path can be absolute, starting with a slash on Unix or a
803817 138   drive letter prefix on Windows.  The path can alternatively be a :term:`asset
SP 139   specification` in the form ``some.dotted.package_name:relative/path``, making
140   it possible to address template assets which live in a separate package.
8a1b50 141
CD 142   The ``renderer`` attribute is optional.  If it is not defined, the "null"
143   renderer is assumed (no rendering is performed and the value is passed back
803817 144   to the upstream :app:`Pyramid` machinery unchanged).  Note that if the view
SP 145   callable itself returns a :term:`response` (see :ref:`the_response`), the
146   specified renderer implementation is never called.
8a1b50 147
0fa199 148 ``http_cache``
CM 149   When you supply an ``http_cache`` value to a view configuration, the
150   ``Expires`` and ``Cache-Control`` headers of a response generated by the
151   associated view callable are modified.  The value for ``http_cache`` may be
152   one of the following:
153
803817 154   - A nonzero integer.  If it's a nonzero integer, it's treated as a number of
SP 155     seconds.  This number of seconds will be used to compute the ``Expires``
156     header and the ``Cache-Control: max-age`` parameter of responses to
157     requests which call this view.  For example: ``http_cache=3600`` instructs
158     the requesting browser to 'cache this response for an hour, please'.
0fa199 159
CM 160   - A ``datetime.timedelta`` instance.  If it's a ``datetime.timedelta``
803817 161     instance, it will be converted into a number of seconds, and that number of
SP 162     seconds will be used to compute the ``Expires`` header and the
0fa199 163     ``Cache-Control: max-age`` parameter of responses to requests which call
CM 164     this view.  For example: ``http_cache=datetime.timedelta(days=1)``
165     instructs the requesting browser to 'cache this response for a day,
166     please'.
167
803817 168   - Zero (``0``).  If the value is zero, the ``Cache-Control`` and ``Expires``
SP 169     headers present in all responses from this view will be composed such that
170     client browser cache (and any intermediate caches) are instructed to never
171     cache the response.
0fa199 172
803817 173   - A two-tuple.  If it's a two-tuple (e.g., ``http_cache=(1,
SP 174     {'public':True})``), the first value in the tuple may be a nonzero integer
175     or a ``datetime.timedelta`` instance. In either case this value will be
176     used as the number of seconds to cache the response.  The second value in
177     the tuple must be a dictionary.  The values present in the dictionary will
178     be used as input to the ``Cache-Control`` response header.  For example:
179     ``http_cache=(3600, {'public':True})`` means 'cache for an hour, and add
180     ``public`` to the Cache-Control header of the response'.  All keys and
181     values supported by the ``webob.cachecontrol.CacheControl`` interface may
182     be added to the dictionary.  Supplying ``{'public':True}`` is equivalent to
183     calling ``response.cache_control.public = True``.
0fa199 184
CM 185   Providing a non-tuple value as ``http_cache`` is equivalent to calling
186   ``response.cache_expires(value)`` within your view's body.
187
188   Providing a two-tuple value as ``http_cache`` is equivalent to calling
189   ``response.cache_expires(value[0], **value[1])`` within your view's body.
190
803817 191   If you wish to avoid influencing the ``Expires`` header, and instead wish to
SP 192   only influence ``Cache-Control`` headers, pass a tuple as ``http_cache`` with
193   the first element of ``None``, i.e., ``(None, {'public':True})``.
0fa199 194
769da1 195
MM 196 ``require_csrf``
197
21d5be 198   CSRF checks will affect any request method that is not defined as a "safe"
DS 199   method by RFC2616. In pratice this means that GET, HEAD, OPTIONS, and TRACE
200   methods will pass untouched and all others methods will require CSRF. This
201   option is used in combination with the ``pyramid.require_default_csrf``
202   setting to control which request parameters are checked for CSRF tokens.
769da1 203
MM 204   This feature requires a configured :term:`session factory`.
205
206   If this option is set to ``True`` then CSRF checks will be enabled for POST
207   requests to this view. The required token will be whatever was specified by
208   the ``pyramid.require_default_csrf`` setting, or will fallback to
209   ``csrf_token``.
210
211   If this option is set to a string then CSRF checks will be enabled and it
212   will be used as the required token regardless of the
213   ``pyramid.require_default_csrf`` setting.
214
215   If this option is set to ``False`` then CSRF checks will be disabled
216   regardless of the ``pyramid.require_default_csrf`` setting.
217
65dee6 218   In addition, if this option is set to ``True`` or a string then CSRF origin
DS 219   checking will be enabled.
220
769da1 221   See :ref:`auto_csrf_checking` for more information.
MM 222
223   .. versionadded:: 1.7
224
8a1b50 225 ``wrapper``
263715 226   The :term:`view name` of a different :term:`view configuration` which will
SP 227   receive the response body of this view as the ``request.wrapped_body``
228   attribute of its own :term:`request`, and the :term:`response` returned by
229   this view as the ``request.wrapped_response`` attribute of its own request.
230   Using a wrapper makes it possible to "chain" views together to form a
231   composite response.  The response of the outermost wrapper view will be
232   returned to the user.  The wrapper view will be found as any view is found.
233   See :ref:`view_lookup`.  The "best" wrapper view will be found based on the
234   lookup ordering. "Under the hood" this wrapper view is looked up via
235   ``pyramid.view.render_view_to_response(context, request,
236   'wrapper_viewname')``. The context and request of a wrapper view is the same
237   context and request of the inner view.
8a1b50 238
263715 239   If ``wrapper`` is not supplied, no wrapper view is used.
8a1b50 240
f7f0dd 241 ``decorator``
86fc0c 242   A :term:`dotted Python name` to a function (or the function itself) which
803817 243   will be used to decorate the registered :term:`view callable`.  The decorator
SP 244   function will be called with the view callable as a single argument.  The
245   view callable it is passed will accept ``(context, request)``.  The decorator
246   must return a replacement view callable which also accepts ``(context,
247   request)``. The ``decorator`` may also be an iterable of decorators, in which
248   case they will be applied one after the other to the view, in reverse order.
249   For example::
df6065 250
MM 251     @view_config(..., decorator=(decorator2, decorator1))
252     def myview(request):
253       ...
254
663c26 255   Is similar to decorating the view callable directly::
df6065 256
MM 257     @view_config(...)
258     @decorator2
259     @decorator1
260     def myview(request):
261       ...
2e3f70 262
663c26 263   An important distinction is that each decorator will receive a response
MM 264   object implementing :class:`pyramid.interfaces.IResponse` instead of the
265   raw value returned from the view callable. All decorators in the chain must
266   return a response object or raise an exception:
6e0f02 267
MM 268   .. code-block:: python
269
6517a9 270       def log_timer(wrapped):
SP 271           def wrapper(context, request):
272               start = time.time()
273               response = wrapped(context, request)
274               duration = time.time() - start
275               response.headers['X-View-Time'] = '%.3f' % (duration,)
276               log.info('view took %.3f seconds', duration)
277               return response
278           return wrapper
6e0f02 279
f7f0dd 280 ``mapper``
CM 281   A Python object or :term:`dotted Python name` which refers to a :term:`view
282   mapper`, or ``None``.  By default it is ``None``, which indicates that the
283   view should use the default view mapper.  This plug-point is useful for
803817 284   Pyramid extension developers, but it's not very useful for "civilians" who
f7f0dd 285   are just developing stock Pyramid applications. Pay no attention to the man
CM 286   behind the curtain.
287
4cc3a6 288 ``accept``
MM 289   A :term:`media type` that will be matched against the ``Accept`` HTTP request header.
290   If this value is specified, it must be a specific media type such as ``text/html`` or ``text/html;level=1``.
291   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.
292   If this does not match the ``Accept`` header of the request, view matching continues.
293
294   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.
295
296   The ``accept`` argument is technically not a predicate and does not support wrapping with :func:`pyramid.config.not_`.
297
298   See :ref:`accept_content_negotiation` for more information.
299
300   .. versionchanged:: 1.10
301
302       Specifying a media range is deprecated and will be removed in :app:`Pyramid` 2.0.
303       Use explicit media types to avoid any ambiguities in content negotiation.
304
121f45 305 ``exception_only``
MM 306
307   When this value is ``True``, the ``context`` argument must be a subclass of
308   ``Exception``. This flag indicates that only an :term:`exception view` should
309   be created, and that this view should not match if the traversal
310   :term:`context` matches the ``context`` argument. If the ``context`` is a
311   subclass of ``Exception`` and this value is ``False`` (the default), then a
312   view will be registered to match the traversal :term:`context` as well.
313
314   .. versionadded:: 1.8
315
8a1b50 316 Predicate Arguments
CD 317 +++++++++++++++++++
318
803817 319 These arguments modify view lookup behavior. In general the more predicate
SP 320 arguments that are supplied, the more specific and narrower the usage of the
8a1b50 321 configured view.
CD 322
323 ``name``
8cb682 324   The :term:`view name` required to match this view callable.  A ``name``
803817 325   argument is typically only used when your application uses :term:`traversal`.
SP 326   Read :ref:`traversal_chapter` to understand the concept of a view name.
8a1b50 327
CD 328   If ``name`` is not supplied, the empty string is used (implying the default
329   view).
330
331 ``context``
803817 332   An object representing a Python class of which the :term:`context` resource
SP 333   must be an instance *or* the :term:`interface` that the :term:`context`
8a1b50 334   resource must provide in order for this view to be found and called.  This
CD 335   predicate is true when the :term:`context` resource is an instance of the
803817 336   represented class or if the :term:`context` resource provides the represented
SP 337   interface; it is otherwise false.
8a1b50 338
e8c66a 339   It is possible to pass an exception class as the context if your context may
160aab 340   subclass an exception. In this case *two* views will be registered. One
SP 341   will match normal incoming requests, and the other will match as an
e8c66a 342   :term:`exception view` which only occurs when an exception is raised during
MM 343   the normal request processing pipeline.
344
8a1b50 345   If ``context`` is not supplied, the value ``None``, which matches any
CD 346   resource, is used.
347
348 ``route_name``
349   If ``route_name`` is supplied, the view callable will be invoked only when
350   the named route has matched.
351
352   This value must match the ``name`` of a :term:`route configuration`
803817 353   declaration (see :ref:`urldispatch_chapter`) that must match before this view
SP 354   will be called.  Note that the ``route`` configuration referred to by
8a1b50 355   ``route_name`` will usually have a ``*traverse`` token in the value of its
CD 356   ``pattern``, representing a part of the path that will be used by
357   :term:`traversal` against the result of the route's :term:`root factory`.
358
2e3f70 359   If ``route_name`` is not supplied, the view callable will only have a chance
8a1b50 360   of being invoked if no other route was matched. This is when the
803817 361   request/context pair found via :term:`resource location` does not indicate it
SP 362   matched any configured route.
8a1b50 363
CD 364 ``request_type``
365   This value should be an :term:`interface` that the :term:`request` must
366   provide in order for this view to be found and called.
367
803817 368   If ``request_type`` is not supplied, the value ``None`` is used, implying any
SP 369   request type.
8a1b50 370
CD 371   *This is an advanced feature, not often used by "civilians"*.
372
373 ``request_method``
306c29 374   This value can be either a string (such as ``"GET"``, ``"POST"``,
803817 375   ``"PUT"``, ``"DELETE"``, ``"HEAD"``, or ``"OPTIONS"``) representing an HTTP
SP 376   ``REQUEST_METHOD`` or a tuple containing one or more of these strings.  A
377   view declaration with this argument ensures that the view will only be called
378   when the ``method`` attribute of the request (i.e., the ``REQUEST_METHOD`` of
379   the WSGI environment) matches a supplied value.
f016cd 380
803817 381   .. versionchanged:: 1.4
SP 382     The use of ``"GET"`` also implies that the view will respond to ``"HEAD"``.
8a1b50 383
803817 384   If ``request_method`` is not supplied, the view will be invoked regardless of
SP 385   the ``REQUEST_METHOD`` of the :term:`WSGI` environment.
8a1b50 386
CD 387 ``request_param``
a62912 388   This value can be any string or a sequence of strings.  A view declaration
SP 389   with this argument ensures that the view will only be called when the
390   :term:`request` has a key in the ``request.params`` dictionary (an HTTP
803817 391   ``GET`` or ``POST`` variable) that has a name which matches the supplied
SP 392   value.
8a1b50 393
803817 394   If any value supplied has an ``=`` sign in it, e.g.,
SP 395   ``request_param="foo=123"``, then the key (``foo``) must both exist in the
396   ``request.params`` dictionary, *and* the value must match the right hand side
397   of the expression (``123``) for the view to "match" the current request.
8a1b50 398
CD 399   If ``request_param`` is not supplied, the view will be invoked without
400   consideration of keys and values in the ``request.params`` dictionary.
401
c0e6e6 402 ``match_param``
803817 403   This param may be either a single string of the format "key=value" or a tuple
SP 404   containing one or more of these strings.
c0e6e6 405
CM 406   This argument ensures that the view will only be called when the
803817 407   :term:`request` has key/value pairs in its :term:`matchdict` that equal those
SP 408   supplied in the predicate.  For example, ``match_param="action=edit"`` would
c0e6e6 409   require the ``action`` parameter in the :term:`matchdict` match the right
dd1c53 410   hand side of the expression (``edit``) for the view to "match" the current
c0e6e6 411   request.
CM 412
803817 413   If the ``match_param`` is a tuple, every key/value pair must match for the
SP 414   predicate to pass.
c0e6e6 415
CM 416   If ``match_param`` is not supplied, the view will be invoked without
417   consideration of the keys and values in ``request.matchdict``.
a62912 418
SP 419   .. versionadded:: 1.2
c0e6e6 420
8a1b50 421 ``containment``
803817 422   This value should be a reference to a Python class or :term:`interface` that
SP 423   a parent object in the context resource's :term:`lineage` must provide in
424   order for this view to be found and called.  The resources in your resource
425   tree must be "location-aware" to use this feature.
8a1b50 426
803817 427   If ``containment`` is not supplied, the interfaces and classes in the lineage
SP 428   are not considered when deciding whether or not to invoke the view callable.
8a1b50 429
CD 430   See :ref:`location_aware` for more information about location-awareness.
431
432 ``xhr``
433   This value should be either ``True`` or ``False``.  If this value is
434   specified and is ``True``, the :term:`WSGI` environment must possess an
803817 435   ``HTTP_X_REQUESTED_WITH`` header (i.e., ``X-Requested-With``) that has the
8a1b50 436   value ``XMLHttpRequest`` for the associated view callable to be found and
CD 437   called.  This is useful for detecting AJAX requests issued from jQuery,
803817 438   Prototype, and other Javascript libraries.
8a1b50 439
803817 440   If ``xhr`` is not specified, the ``HTTP_X_REQUESTED_WITH`` HTTP header is not
SP 441   taken into consideration when deciding whether or not to invoke the
8a1b50 442   associated view callable.
CD 443
444 ``header``
445   This value represents an HTTP header name or a header name/value pair.
446
447   If ``header`` is specified, it must be a header name or a
448   ``headername:headervalue`` pair.
449
803817 450   If ``header`` is specified without a value (a bare header name only, e.g.,
SP 451   ``If-Modified-Since``), the view will only be invoked if the HTTP header
452   exists with any value in the request.
8a1b50 453
803817 454   If ``header`` is specified, and possesses a name/value pair (e.g.,
SP 455   ``User-Agent:Mozilla/.*``), the view will only be invoked if the HTTP header
456   exists *and* the HTTP header matches the value requested.  When the
457   ``headervalue`` contains a ``:`` (colon), it will be considered a name/value
458   pair (e.g., ``User-Agent:Mozilla/.*`` or ``Host:localhost``).  The value
459   portion should be a regular expression.
8a1b50 460
CD 461   Whether or not the value represents a header name or a header name/value
462   pair, the case of the header name is not significant.
463
803817 464   If ``header`` is not specified, the composition, presence, or absence of HTTP
SP 465   headers is not taken into consideration when deciding whether or not to
466   invoke the associated view callable.
8a1b50 467
CD 468 ``path_info``
469   This value represents a regular expression pattern that will be tested
803817 470   against the ``PATH_INFO`` WSGI environment variable to decide whether or not
SP 471   to call the associated view callable.  If the regex matches, this predicate
472   will be ``True``.
8a1b50 473
CD 474   If ``path_info`` is not specified, the WSGI ``PATH_INFO`` is not taken into
475   consideration when deciding whether or not to invoke the associated view
476   callable.
477
643a83 478 ``check_csrf``
803817 479   If specified, this value should be one of ``None``, ``True``, ``False``, or a
SP 480   string representing the "check name".  If the value is ``True`` or a string,
481   CSRF checking will be performed.  If the value is ``False`` or ``None``, CSRF
482   checking will not be performed.
643a83 483
803817 484   If the value provided is a string, that string will be used as the "check
SP 485   name".  If the value provided is ``True``, ``csrf_token`` will be used as the
486   check name.
643a83 487
CM 488   If CSRF checking is performed, the checked value will be the value of
f12005 489   ``request.POST[check_name]``.  This value will be compared against the
643a83 490   value of ``request.session.get_csrf_token()``, and the check will pass if
803817 491   these two values are the same.  If the check passes, the associated view will
SP 492   be permitted to execute.  If the check fails, the associated view will not be
493   permitted to execute.
643a83 494
803817 495   Note that using this feature requires a :term:`session factory` to have been
SP 496   configured.
643a83 497
CM 498   .. versionadded:: 1.4a2
499
c25a8f 500 ``physical_path``
CM 501   If specified, this value should be a string or a tuple representing the
502   :term:`physical path` of the context found via traversal for this predicate
803817 503   to match as true.  For example, ``physical_path='/'``,
SP 504   ``physical_path='/a/b/c'``, or ``physical_path=('', 'a', 'b', 'c')``.  This
505   is not a path prefix match or a regex, but a whole-path match.  It's useful
c25a8f 506   when you want to always potentially show a view when some object is traversed
CM 507   to, but you can't be sure about what kind of object it will be, so you can't
803817 508   use the ``context`` predicate.  The individual path elements between slash
c25a8f 509   characters or in tuple elements should be the Unicode representation of the
CM 510   name of the resource and should not be encoded in any way.
511
512   .. versionadded:: 1.4a3
513
c7337b 514 ``effective_principals``
CM 515   If specified, this value should be a :term:`principal` identifier or a
516   sequence of principal identifiers.  If the
803817 517   :meth:`pyramid.request.Request.effective_principals` method indicates that
SP 518   every principal named in the argument list is present in the current request,
519   this predicate will return True; otherwise it will return False.  For
520   example: ``effective_principals=pyramid.security.Authenticated`` or
c7337b 521   ``effective_principals=('fred', 'group:admins')``.
CM 522
523   .. versionadded:: 1.4a4
524
8a1b50 525 ``custom_predicates``
803817 526   If ``custom_predicates`` is specified, it must be a sequence of references to
SP 527   custom predicate callables.  Use custom predicates when no set of predefined
528   predicates do what you need.  Custom predicates can be combined with
529   predefined predicates as necessary.  Each custom predicate callable should
530   accept two arguments, ``context`` and ``request``, and should return either
531   ``True`` or ``False`` after doing arbitrary evaluation of the context
532   resource and/or the request.  If all callables return ``True``, the
8a1b50 533   associated view callable will be considered viable for a given request.
CD 534
803817 535   If ``custom_predicates`` is not specified, no custom predicates are used.
8a1b50 536
643a83 537 ``predicates``
CM 538   Pass a key/value pair here to use a third-party predicate registered via
539   :meth:`pyramid.config.Configurator.add_view_predicate`.  More than one
540   key/value pair can be used at the same time.  See
541   :ref:`view_and_route_predicates` for more information about third-party
542   predicates.
543
544   .. versionadded:: 1.4a1
545
aa7b06 546 Inverting Predicate Values
CM 547 ++++++++++++++++++++++++++
548
549 You can invert the meaning of any predicate value by wrapping it in a call to
550 :class:`pyramid.config.not_`.
551
552 .. code-block:: python
6517a9 553     :linenos:
aa7b06 554
6517a9 555     from pyramid.config import not_
aa7b06 556
6517a9 557     config.add_view(
SP 558         'mypackage.views.my_view',
559         route_name='ok',
560         request_method=not_('POST')
561         )
aa7b06 562
803817 563 The above example will ensure that the view is called if the request method is
SP 564 *not* ``POST``, at least if no other view is more specific.
aa7b06 565
CM 566 This technique of wrapping a predicate value in ``not_`` can be used anywhere
567 predicate values are accepted:
568
569 - :meth:`pyramid.config.Configurator.add_view`
570
571 - :meth:`pyramid.view.view_config`
572
573 .. versionadded:: 1.5
574
575
8a1b50 576 .. index::
CD 577    single: view_config decorator
578
579 .. _mapping_views_using_a_decorator_section:
580
e81ad8 581 Adding View Configuration Using the ``@view_config`` Decorator
CM 582 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8a1b50 583
CD 584 .. warning::
585
803817 586    Using this feature tends to slow down application startup slightly, as more
SP 587    work is performed at application startup to scan for view configuration
588    declarations.  For maximum startup performance, use the view configuration
589    method described in :ref:`mapping_views_using_imperative_config_section`
590    instead.
8a1b50 591
e81ad8 592 The :class:`~pyramid.view.view_config` decorator can be used to associate
CM 593 :term:`view configuration` information with a function, method, or class that
594 acts as a :app:`Pyramid` view callable.
8a1b50 595
026da8 596 Here's an example of the :class:`~pyramid.view.view_config` decorator that
CM 597 lives within a :app:`Pyramid` application module ``views.py``:
8a1b50 598
CD 599 .. code-block:: python
6517a9 600     :linenos:
8a1b50 601
6517a9 602     from resources import MyResource
SP 603     from pyramid.view import view_config
604     from pyramid.response import Response
8a1b50 605
6517a9 606     @view_config(route_name='ok', request_method='POST', permission='read')
SP 607     def my_view(request):
608         return Response('OK')
8a1b50 609
CD 610 Using this decorator as above replaces the need to add this imperative
611 configuration stanza:
612
613 .. code-block:: python
6517a9 614     :linenos:
8a1b50 615
6517a9 616     config.add_view('mypackage.views.my_view', route_name='ok',
SP 617                     request_method='POST', permission='read')
8a1b50 618
CD 619 All arguments to ``view_config`` may be omitted.  For example:
620
621 .. code-block:: python
6517a9 622     :linenos:
8a1b50 623
6517a9 624     from pyramid.response import Response
SP 625     from pyramid.view import view_config
8a1b50 626
6517a9 627     @view_config()
SP 628     def my_view(request):
629         """ My view """
630         return Response()
8a1b50 631
CD 632 Such a registration as the one directly above implies that the view name will
633 be ``my_view``, registered with a ``context`` argument that matches any
634 resource type, using no permission, registered against requests with any
635 request method, request type, request param, route name, or containment.
636
637 The mere existence of a ``@view_config`` decorator doesn't suffice to perform
638 view configuration.  All that the decorator does is "annotate" the function
639 with your configuration declarations, it doesn't process them. To make
803817 640 :app:`Pyramid` process your :class:`pyramid.view.view_config` declarations, you
SP 641 *must* use the ``scan`` method of a :class:`pyramid.config.Configurator`:
8a1b50 642
CD 643 .. code-block:: python
6517a9 644     :linenos:
8a1b50 645
6517a9 646     # config is assumed to be an instance of the
SP 647     # pyramid.config.Configurator class
648     config.scan()
8a1b50 649
803817 650 Please see :ref:`decorations_and_code_scanning` for detailed information about
SP 651 what happens when code is scanned for configuration declarations resulting from
652 use of decorators like :class:`~pyramid.view.view_config`.
8a1b50 653
CD 654 See :ref:`configuration_module` for additional API arguments to the
70acd2 655 :meth:`~pyramid.config.Configurator.scan` method.  For example, the method
8a1b50 656 allows you to supply a ``package`` argument to better control exactly *which*
CD 657 code will be scanned.
e81ad8 658
CM 659 All arguments to the :class:`~pyramid.view.view_config` decorator mean
803817 660 precisely the same thing as they would if they were passed as arguments to the
SP 661 :meth:`pyramid.config.Configurator.add_view` method save for the ``view``
662 argument.  Usage of the :class:`~pyramid.view.view_config` decorator is a form
663 of :term:`declarative configuration`, while
e81ad8 664 :meth:`pyramid.config.Configurator.add_view` is a form of :term:`imperative
CM 665 configuration`.  However, they both do the same thing.
8a1b50 666
6ce1e0 667 .. index::
CM 668    single: view_config placement
669
bb93cb 670 .. _view_config_placement:
CM 671
8a1b50 672 ``@view_config`` Placement
CD 673 ++++++++++++++++++++++++++
674
70acd2 675 A :class:`~pyramid.view.view_config` decorator can be placed in various points
8a1b50 676 in your application.
CD 677
678 If your view callable is a function, it may be used as a function decorator:
679
680 .. code-block:: python
6517a9 681     :linenos:
8a1b50 682
6517a9 683     from pyramid.view import view_config
SP 684     from pyramid.response import Response
8a1b50 685
6517a9 686     @view_config(route_name='edit')
SP 687     def edit(request):
688         return Response('edited!')
8a1b50 689
CD 690 If your view callable is a class, the decorator can also be used as a class
803817 691 decorator. All the arguments to the decorator are the same when applied against
SP 692 a class as when they are applied against a function.  For example:
8a1b50 693
CD 694 .. code-block:: python
6517a9 695     :linenos:
8a1b50 696
6517a9 697     from pyramid.response import Response
SP 698     from pyramid.view import view_config
8a1b50 699
6517a9 700     @view_config(route_name='hello')
SP 701     class MyView(object):
702         def __init__(self, request):
703             self.request = request
8a1b50 704
6517a9 705         def __call__(self):
SP 706             return Response('hello')
8a1b50 707
70acd2 708 More than one :class:`~pyramid.view.view_config` decorator can be stacked on
8a1b50 709 top of any number of others.  Each decorator creates a separate view
CD 710 registration.  For example:
711
712 .. code-block:: python
6517a9 713     :linenos:
8a1b50 714
6517a9 715     from pyramid.view import view_config
SP 716     from pyramid.response import Response
8a1b50 717
6517a9 718     @view_config(route_name='edit')
SP 719     @view_config(route_name='change')
720     def edit(request):
721         return Response('edited!')
8a1b50 722
CD 723 This registers the same view under two different names.
724
2e3f70 725 The decorator can also be used against a method of a class:
8a1b50 726
CD 727 .. code-block:: python
6517a9 728     :linenos:
8a1b50 729
6517a9 730     from pyramid.response import Response
SP 731     from pyramid.view import view_config
8a1b50 732
6517a9 733     class MyView(object):
SP 734         def __init__(self, request):
735             self.request = request
8a1b50 736
6517a9 737         @view_config(route_name='hello')
SP 738         def amethod(self):
739             return Response('hello')
8a1b50 740
2e3f70 741 When the decorator is used against a method of a class, a view is registered
CZ 742 for the *class*, so the class constructor must accept an argument list in one
803817 743 of two forms: either a single argument, ``request``, or two arguments,
SP 744 ``context, request``.
8a1b50 745
CD 746 The method which is decorated must return a :term:`response`.
747
748 Using the decorator against a particular method of a class is equivalent to
803817 749 using the ``attr`` parameter in a decorator attached to the class itself. For
SP 750 example, the above registration implied by the decorator being used against the
751 ``amethod`` method could be written equivalently as follows:
8a1b50 752
CD 753 .. code-block:: python
6517a9 754     :linenos:
8a1b50 755
6517a9 756     from pyramid.response import Response
SP 757     from pyramid.view import view_config
8a1b50 758
6517a9 759     @view_config(attr='amethod', route_name='hello')
SP 760     class MyView(object):
761         def __init__(self, request):
762             self.request = request
8a1b50 763
6517a9 764         def amethod(self):
SP 765             return Response('hello')
8a1b50 766
4375cf 767
8a1b50 768 .. index::
CD 769    single: add_view
770
771 .. _mapping_views_using_imperative_config_section:
772
e81ad8 773 Adding View Configuration Using :meth:`~pyramid.config.Configurator.add_view`
CM 774 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8a1b50 775
CD 776 The :meth:`pyramid.config.Configurator.add_view` method within
803817 777 :ref:`configuration_module` is used to configure a view "imperatively" (without
SP 778 a :class:`~pyramid.view.view_config` decorator).  The arguments to this method
779 are very similar to the arguments that you provide to the
026da8 780 :class:`~pyramid.view.view_config` decorator.  For example:
8a1b50 781
CD 782 .. code-block:: python
6517a9 783     :linenos:
8a1b50 784
6517a9 785     from pyramid.response import Response
8a1b50 786
6517a9 787     def hello_world(request):
SP 788         return Response('hello!')
8a1b50 789
6517a9 790     # config is assumed to be an instance of the
SP 791     # pyramid.config.Configurator class
792     config.add_view(hello_world, route_name='hello')
8a1b50 793
803817 794 The first argument, a :term:`view callable`, is the only required argument. It
SP 795 must either be a Python object which is the view itself or a :term:`dotted
796 Python name` to such an object. In the above example, the ``view callable`` is
797 the ``hello_world`` function.
026da8 798
CM 799 When you use only :meth:`~pyramid.config.Configurator.add_view` to add view
800 configurations, you don't need to issue a :term:`scan` in order for the view
801 configuration to take effect.
8a1b50 802
CD 803 .. index::
4375cf 804    single: view_defaults class decorator
CM 805
806 .. _view_defaults:
807
808 ``@view_defaults`` Class Decorator
809 ----------------------------------
810
40dbf4 811 .. versionadded:: 1.3
4375cf 812
CM 813 If you use a class as a view, you can use the
814 :class:`pyramid.view.view_defaults` class decorator on the class to provide
815 defaults to the view configuration information used by every ``@view_config``
816 decorator that decorates a method of that class.
817
818 For instance, if you've got a class that has methods that represent "REST
803817 819 actions", all of which are mapped to the same route but different request
4375cf 820 methods, instead of this:
CM 821
822 .. code-block:: python
6517a9 823     :linenos:
4375cf 824
6517a9 825     from pyramid.view import view_config
SP 826     from pyramid.response import Response
4375cf 827
6517a9 828     class RESTView(object):
SP 829         def __init__(self, request):
830             self.request = request
4375cf 831
6517a9 832         @view_config(route_name='rest', request_method='GET')
SP 833         def get(self):
834             return Response('get')
4375cf 835
6517a9 836         @view_config(route_name='rest', request_method='POST')
SP 837         def post(self):
838             return Response('post')
4375cf 839
6517a9 840         @view_config(route_name='rest', request_method='DELETE')
SP 841         def delete(self):
842             return Response('delete')
4375cf 843
CM 844 You can do this:
845
846 .. code-block:: python
6517a9 847     :linenos:
4375cf 848
6517a9 849     from pyramid.view import view_defaults
SP 850     from pyramid.view import view_config
851     from pyramid.response import Response
4375cf 852
6517a9 853     @view_defaults(route_name='rest')
SP 854     class RESTView(object):
855         def __init__(self, request):
856             self.request = request
4375cf 857
6517a9 858         @view_config(request_method='GET')
SP 859         def get(self):
860             return Response('get')
4375cf 861
6517a9 862         @view_config(request_method='POST')
SP 863         def post(self):
864             return Response('post')
4375cf 865
6517a9 866         @view_config(request_method='DELETE')
SP 867         def delete(self):
868             return Response('delete')
4375cf 869
CM 870 In the above example, we were able to take the ``route_name='rest'`` argument
803817 871 out of the call to each individual ``@view_config`` statement because we used a
SP 872 ``@view_defaults`` class decorator to provide the argument as a default to each
873 view method it possessed.
4375cf 874
CM 875 Arguments passed to ``@view_config`` will override any default passed to
876 ``@view_defaults``.
877
878 The ``view_defaults`` class decorator can also provide defaults to the
879 :meth:`pyramid.config.Configurator.add_view` directive when a decorated class
803817 880 is passed to that directive as its ``view`` argument.  For example, instead of
SP 881 this:
4375cf 882
CM 883 .. code-block:: python
6517a9 884     :linenos:
4375cf 885
6517a9 886     from pyramid.response import Response
SP 887     from pyramid.config import Configurator
4375cf 888
6517a9 889     class RESTView(object):
SP 890         def __init__(self, request):
891             self.request = request
4375cf 892
6517a9 893         def get(self):
SP 894             return Response('get')
4375cf 895
6517a9 896         def post(self):
SP 897             return Response('post')
4375cf 898
6517a9 899         def delete(self):
SP 900             return Response('delete')
4375cf 901
6517a9 902     def main(global_config, **settings):
SP 903         config = Configurator()
904         config.add_route('rest', '/rest')
905         config.add_view(
906             RESTView, route_name='rest', attr='get', request_method='GET')
907         config.add_view(
908             RESTView, route_name='rest', attr='post', request_method='POST')
909         config.add_view(
910             RESTView, route_name='rest', attr='delete', request_method='DELETE')
911         return config.make_wsgi_app()
4375cf 912
c40d20 913 To reduce the amount of repetition in the ``config.add_view`` statements, we
1e35e0 914 can move the ``route_name='rest'`` argument to a ``@view_defaults`` class
803817 915 decorator on the ``RESTView`` class:
4375cf 916
CM 917 .. code-block:: python
6517a9 918     :linenos:
4375cf 919
6517a9 920     from pyramid.view import view_defaults
SP 921     from pyramid.response import Response
922     from pyramid.config import Configurator
4375cf 923
6517a9 924     @view_defaults(route_name='rest')
SP 925     class RESTView(object):
926         def __init__(self, request):
927             self.request = request
4375cf 928
6517a9 929         def get(self):
SP 930             return Response('get')
4375cf 931
6517a9 932         def post(self):
SP 933             return Response('post')
4375cf 934
6517a9 935         def delete(self):
SP 936             return Response('delete')
4375cf 937
6517a9 938     def main(global_config, **settings):
SP 939         config = Configurator()
940         config.add_route('rest', '/rest')
941         config.add_view(RESTView, attr='get', request_method='GET')
942         config.add_view(RESTView, attr='post', request_method='POST')
943         config.add_view(RESTView, attr='delete', request_method='DELETE')
944         return config.make_wsgi_app()
4375cf 945
CM 946 :class:`pyramid.view.view_defaults` accepts the same set of arguments that
947 :class:`pyramid.view.view_config` does, and they have the same meaning.  Each
948 argument passed to ``view_defaults`` provides a default for the view
949 configurations of methods of the class it's decorating.
950
803817 951 Normal Python inheritance rules apply to defaults added via ``view_defaults``.
SP 952 For example:
4375cf 953
CM 954 .. code-block:: python
6517a9 955     :linenos:
4375cf 956
6517a9 957     @view_defaults(route_name='rest')
SP 958     class Foo(object):
959         pass
4375cf 960
6517a9 961     class Bar(Foo):
SP 962         pass
4375cf 963
CM 964 The ``Bar`` class above will inherit its view defaults from the arguments
965 passed to the ``view_defaults`` decorator of the ``Foo`` class.  To prevent
803817 966 this from happening, use a ``view_defaults`` decorator without any arguments on
SP 967 the subclass:
4375cf 968
CM 969 .. code-block:: python
6517a9 970     :linenos:
4375cf 971
6517a9 972     @view_defaults(route_name='rest')
SP 973     class Foo(object):
974         pass
4375cf 975
6517a9 976     @view_defaults()
SP 977     class Bar(Foo):
978         pass
4375cf 979
CM 980 The ``view_defaults`` decorator only works as a class decorator; using it
981 against a function or a method will produce nonsensical results.
982
983 .. index::
8a1b50 984    single: view security
CD 985    pair: security; view
986
987 .. _view_security_section:
988
989 Configuring View Security
990 ~~~~~~~~~~~~~~~~~~~~~~~~~
991
992 If an :term:`authorization policy` is active, any :term:`permission` attached
803817 993 to a :term:`view configuration` found during view lookup will be verified. This
SP 994 will ensure that the currently authenticated user possesses that permission
995 against the :term:`context` resource before the view function is actually
996 called.  Here's an example of specifying a permission in a view configuration
997 using :meth:`~pyramid.config.Configurator.add_view`:
8a1b50 998
CD 999 .. code-block:: python
6517a9 1000     :linenos:
8a1b50 1001
6517a9 1002     # config is an instance of pyramid.config.Configurator
8a1b50 1003
6517a9 1004     config.add_route('add', '/add.html', factory='mypackage.Blog')
SP 1005     config.add_view('myproject.views.add_entry', route_name='add',
1006                     permission='add')
8a1b50 1007
CD 1008 When an :term:`authorization policy` is enabled, this view will be protected
1009 with the ``add`` permission.  The view will *not be called* if the user does
1010 not possess the ``add`` permission relative to the current :term:`context`.
803817 1011 Instead the :term:`forbidden view` result will be returned to the client as per
SP 1012 :ref:`protecting_views`.
8a1b50 1013
CD 1014 .. index::
1015    single: debugging not found errors
1016    single: not found error (debugging)
1017
1018 .. _debug_notfound_section:
1019
f758ec 1020 :exc:`~pyramid.exceptions.NotFound` Errors
TL 1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8a1b50 1022
803817 1023 It's useful to be able to debug :exc:`~pyramid.exceptions.NotFound` error
SP 1024 responses when they occur unexpectedly due to an application registry
1025 misconfiguration.  To debug these errors, use the ``PYRAMID_DEBUG_NOTFOUND``
1026 environment variable or the ``pyramid.debug_notfound`` configuration file
1027 setting.  Details of why a view was not found will be printed to ``stderr``,
f016cd 1028 and the browser representation of the error will include the same information.
803817 1029 See :ref:`environment_chapter` for more information about how, and where to set
SP 1030 these values.
8a1b50 1031
8abf0a 1032 .. index::
30f79d 1033    single: Accept
f081ae 1034    single: Accept content negotiation
e573d4 1035
f081ae 1036 .. _accept_content_negotiation:
121f45 1037
MM 1038 Accept Header Content Negotiation
1039 ---------------------------------
1040
1041 The ``accept`` argument to :meth:`pyramid.config.Configurator.add_view` can be used to control :term:`view lookup` by dispatching to different views based on the HTTP ``Accept`` request header.
ed6ddc 1042 Consider the example below in which there are three defined views.
MM 1043 Each view uses the ``Accept`` header to trigger an appropriate response renderer.
121f45 1044
MM 1045 .. code-block:: python
1046
ed6ddc 1047     from pyramid.httpexceptions import HTTPNotAcceptable
121f45 1048     from pyramid.view import view_config
MM 1049
1050     @view_config(accept='application/json', renderer='json')
1051     @view_config(accept='text/html', renderer='templates/hello.jinja2')
1052     def myview(request):
1053         return {
1054             'name': request.GET.get('name', 'bob'),
1055         }
1056
ed6ddc 1057     @view_config()
MM 1058     def myview_unacceptable(request):
1059         raise HTTPNotAcceptable
121f45 1060
MM 1061 The appropriate view is selected here when the client specifies an unambiguous header such as ``Accept: text/*`` or ``Accept: application/json``.
ed6ddc 1062 Similarly, if the client specifies a media type that no view is registered to handle, such as ``Accept: text/plain``, it will fall through to ``myview_unacceptable`` and raise ``406 Not Acceptable``.
MM 1063 There are a few cases in which the client may specify ambiguous constraints:
1064
1065 - ``Accept: */*``.
30f79d 1066 - More than one acceptable media type with the same quality.
ed6ddc 1067 - A missing ``Accept`` header.
MM 1068 - An invalid ``Accept`` header.
1069
30f79d 1070 In these cases the preferred view is not clearly defined (see :rfc:`7231#section-5.3.2`) and :app:`Pyramid` will select one semi-randomly.
ed6ddc 1071 This can be controlled by telling :app:`Pyramid` what the preferred relative ordering is between various media types by using :meth:`pyramid.config.Configurator.add_accept_view_order`.
121f45 1072 For example:
MM 1073
1074 .. code-block:: python
1075
1076     from pyramid.config import Configurator
1077
1078     def main(global_config, **settings):
1079         config = Configurator(settings=settings)
ed6ddc 1080         config.add_accept_view_order('text/html')
MM 1081         config.add_accept_view_order(
121f45 1082             'application/json',
MM 1083             weighs_more_than='text/html',
1084         )
1085         config.scan()
1086         return config.make_wsgi_app()
1087
ed6ddc 1088 In this case, the ``application/json`` view should always be selected in cases where it is otherwise ambiguous.
121f45 1089
f081ae 1090 .. index::
MM 1091     single: default accept ordering
1092
30f79d 1093 .. _default_accept_ordering:
MM 1094
ed6ddc 1095 Default Accept Ordering
ae79df 1096 ~~~~~~~~~~~~~~~~~~~~~~~
30f79d 1097
MM 1098 :app:`Pyramid` will always sort multiple views with the same ``(name, context, route_name)`` first by the specificity of the ``accept`` offer.
4a9f4f 1099 For any set of media type offers with the same ``type/subtype``, the offers with params will weigh more than the bare ``type/subtype`` offer.
MM 1100 This means that ``text/plain;charset=utf8`` will always be offered before ``text/plain``.
30f79d 1101
4a9f4f 1102 By default, within a given ``type/subtype``, the order of offers is ambiguous. For example, ``text/plain;charset=utf8`` versus ``text/plain;charset=latin1`` are sorted in an unspecified way. Similarly, between media types the order is also unspecified other than the defaults described below. For example, ``image/jpeg`` versus ``image/png`` versus ``application/pdf``. In these cases, the ordering may be controlled using :meth:`pyramid.config.Configurator.add_accept_view_order`. For example, to sort ``text/plain`` higher than ``text/html`` and to prefer a ``charset=utf8`` versus a ``charset=latin-1`` within the ``text/plain`` media type:
30f79d 1103
MM 1104 .. code-block:: python
1105
1106     config.add_accept_view_order('text/plain', weighs_more_than='text/html')
1107     config.add_accept_view_order('text/plain;charset=utf8', weighs_more_than='text/plain;charset=latin-1')
1108
4a9f4f 1109 It is an error to try and sort accept headers across levels of specificity. You can only sort a ``type/subtype`` against another ``type/subtype``, not against a ``type/subtype;params``. That ordering is a hard requirement.
121f45 1110
ed6ddc 1111 By default, :app:`Pyramid` defines a very simple priority ordering for views that prefers human-readable responses over JSON:
121f45 1112
ed6ddc 1113 - ``text/html``
MM 1114 - ``application/xhtml+xml``
1115 - ``application/xml``
1116 - ``text/xml``
1117 - ``text/plain``
1118 - ``application/json``
1119
1120 API clients tend to be able to specify their desired headers with more control than web browsers, and can specify the correct ``Accept`` value, if necessary.
1121 Therefore, the motivation for this ordering is to optimize for readability.
1122 Media types that are not listed above are ordered randomly during :term:`view lookup` between otherwise-similar views.
1123 The defaults can be overridden using :meth:`pyramid.config.Configurator.add_accept_view_order` as described above.
121f45 1124
30f79d 1125 .. index::
MM 1126    single: HTTP caching
1127
e573d4 1128 .. _influencing_http_caching:
CM 1129
1130 Influencing HTTP Caching
1131 ------------------------
1132
40dbf4 1133 .. versionadded:: 1.1
e573d4 1134
803817 1135 When a non-``None`` ``http_cache`` argument is passed to a view configuration,
SP 1136 Pyramid will set ``Expires`` and ``Cache-Control`` response headers in the
1137 resulting response, causing browsers to cache the response data for some time.
1138 See ``http_cache`` in :ref:`nonpredicate_view_args` for the allowable values
1139 and what they mean.
e573d4 1140
803817 1141 Sometimes it's undesirable to have these headers set as the result of returning
SP 1142 a response from a view, even though you'd like to decorate the view with a view
1143 configuration decorator that has ``http_cache``.  Perhaps there's an
1144 alternative branch in your view code that returns a response that should never
1145 be cacheable, while the "normal" branch returns something that should always be
1146 cacheable.  If this is the case, set the ``prevent_auto`` attribute of the
1147 ``response.cache_control`` object to a non-``False`` value.  For example, the
1148 below view callable is configured with a ``@view_config`` decorator that
1149 indicates any response from the view should be cached for 3600 seconds.
1150 However, the view itself prevents caching from taking place unless there's a
1151 ``should_cache`` GET or POST variable:
e573d4 1152
CM 1153 .. code-block:: python
1154
6517a9 1155     from pyramid.view import view_config
e573d4 1156
6517a9 1157     @view_config(http_cache=3600)
SP 1158     def view(request):
1159         response = Response()
1160         if 'should_cache' not in request.params:
1161             response.cache_control.prevent_auto = True
1162         return response
e573d4 1163
803817 1164 Note that the ``http_cache`` machinery will overwrite or add to caching headers
SP 1165 you set within the view itself, unless you use ``prevent_auto``.
e573d4 1166
803817 1167 You can also turn off the effect of ``http_cache`` entirely for the duration of
SP 1168 a Pyramid application lifetime.  To do so, set the
e573d4 1169 ``PYRAMID_PREVENT_HTTP_CACHE`` environment variable or the
803817 1170 ``pyramid.prevent_http_cache`` configuration value setting to a true value. For
SP 1171 more information, see :ref:`preventing_http_caching`.
e573d4 1172
875ded 1173 Note that setting ``pyramid.prevent_http_cache`` will have no effect on caching
5fa17f 1174 headers that your application code itself sets.  It will only prevent caching
803817 1175 headers that would have been set by the Pyramid HTTP caching machinery invoked
SP 1176 as the result of the ``http_cache`` argument to view configuration.
5fa17f 1177
6ce1e0 1178 .. index::
CM 1179    pair: view configuration; debugging
1180
49d634 1181 .. _debugging_view_configuration:
PE 1182
8cb682 1183 Debugging View Configuration
ae4c57 1184 ----------------------------
8abf0a 1185
ae4c57 1186 See :ref:`displaying_matching_views` for information about how to display
CM 1187 each of the view callables that might match for a given URL.  This can be an
1188 effective way to figure out why a particular view callable is being called
1189 instead of the one you'd like to be called.