forked from Pylons/pyramid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.py
791 lines (618 loc) · 29 KB
/
view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
import inspect
import itertools
import sys
import venusian
from zope.interface import providedBy
from pyramid.exceptions import ConfigurationError, PredicateMismatch
from pyramid.httpexceptions import (
HTTPNotFound,
HTTPTemporaryRedirect,
default_exceptionresponse_view,
)
from pyramid.interfaces import (
IExceptionViewClassifier,
IMultiView,
IRequest,
IRoutesMapper,
ISecuredView,
IView,
IViewClassifier,
)
from pyramid.threadlocal import get_current_registry, manager
from pyramid.util import hide_attrs, reraise as reraise_
_marker = object()
def render_view_to_response(context, request, name='', secure=True):
"""Call the :term:`view callable` configured with a :term:`view
configuration` that matches the :term:`view name` ``name``
registered against the specified ``context`` and ``request`` and
return a :term:`response` object. This function will return
``None`` if a corresponding :term:`view callable` cannot be found
(when no :term:`view configuration` matches the combination of
``name`` / ``context`` / and ``request``).
If `secure`` is ``True``, and the :term:`view callable` found is
protected by a permission, the permission will be checked before calling
the view function. If the permission check disallows view execution
(based on the current :term:`authorization policy`), a
:exc:`pyramid.httpexceptions.HTTPForbidden` exception will be raised.
The exception's ``args`` attribute explains why the view access was
disallowed.
If ``secure`` is ``False``, no permission checking is done."""
registry = getattr(request, 'registry', None)
if registry is None:
registry = get_current_registry()
context_iface = providedBy(context)
# We explicitly pass in the interfaces provided by the request as
# request_iface to _call_view; we don't want _call_view to use
# request.request_iface, because render_view_to_response and friends are
# pretty much limited to finding views that are not views associated with
# routes, and the only thing request.request_iface is used for is to find
# route-based views. The render_view_to_response API is (and always has
# been) a stepchild API reserved for use of those who actually use
# traversal. Doing this fixes an infinite recursion bug introduced in
# Pyramid 1.6a1, and causes the render_view* APIs to behave as they did in
# 1.5 and previous. We should probably provide some sort of different API
# that would allow people to find views for routes. See
# https://github.com/Pylons/pyramid/issues/1643 for more info.
request_iface = providedBy(request)
response = _call_view(
registry,
request,
context,
context_iface,
name,
secure=secure,
request_iface=request_iface,
)
return response # NB: might be None
def render_view_to_iterable(context, request, name='', secure=True):
"""Call the :term:`view callable` configured with a :term:`view
configuration` that matches the :term:`view name` ``name``
registered against the specified ``context`` and ``request`` and
return an iterable object which represents the body of a response.
This function will return ``None`` if a corresponding :term:`view
callable` cannot be found (when no :term:`view configuration`
matches the combination of ``name`` / ``context`` / and
``request``). Additionally, this function will raise a
:exc:`ValueError` if a view function is found and called but the
view function's result does not have an ``app_iter`` attribute.
You can usually get the bytestring representation of the return value of
this function by calling ``b''.join(iterable)``, or just use
:func:`pyramid.view.render_view` instead.
If ``secure`` is ``True``, and the view is protected by a permission, the
permission will be checked before the view function is invoked. If the
permission check disallows view execution (based on the current
:term:`security policy`), a
:exc:`pyramid.httpexceptions.HTTPForbidden` exception will be raised; its
``args`` attribute explains why the view access was disallowed.
If ``secure`` is ``False``, no permission checking is
done."""
response = render_view_to_response(context, request, name, secure)
if response is None:
return None
return response.app_iter
def render_view(context, request, name='', secure=True):
"""Call the :term:`view callable` configured with a :term:`view
configuration` that matches the :term:`view name` ``name``
registered against the specified ``context`` and ``request``
and unwind the view response's ``app_iter`` (see
:ref:`the_response`) into a single bytestring. This function will
return ``None`` if a corresponding :term:`view callable` cannot be
found (when no :term:`view configuration` matches the combination
of ``name`` / ``context`` / and ``request``). Additionally, this
function will raise a :exc:`ValueError` if a view function is
found and called but the view function's result does not have an
``app_iter`` attribute. This function will return ``None`` if a
corresponding view cannot be found.
If ``secure`` is ``True``, and the view is protected by a permission, the
permission will be checked before the view is invoked. If the permission
check disallows view execution (based on the current :term:`authorization
policy`), a :exc:`pyramid.httpexceptions.HTTPForbidden` exception will be
raised; its ``args`` attribute explains why the view access was
disallowed.
If ``secure`` is ``False``, no permission checking is done."""
iterable = render_view_to_iterable(context, request, name, secure)
if iterable is None:
return None
return b''.join(iterable)
class view_config:
"""A function, class or method :term:`decorator` which allows a
developer to create view registrations nearer to a :term:`view
callable` definition than use :term:`imperative
configuration` to do the same.
For example, this code in a module ``views.py``::
from resources import MyResource
@view_config(name='my_view', context=MyResource, permission='read',
route_name='site1')
def my_view(context, request):
return 'OK'
Might replace the following call to the
:meth:`pyramid.config.Configurator.add_view` method::
import views
from resources import MyResource
config.add_view(views.my_view, context=MyResource, name='my_view',
permission='read', route_name='site1')
.. note: :class:`pyramid.view.view_config` is also importable, for
backwards compatibility purposes, as the name
:class:`pyramid.view.bfg_view`.
:class:`pyramid.view.view_config` supports the following keyword
arguments: ``context``, ``exception``, ``permission``, ``name``,
``request_type``, ``route_name``, ``request_method``, ``request_param``,
``containment``, ``xhr``, ``accept``, ``header``, ``path_info``,
``custom_predicates``, ``decorator``, ``mapper``, ``http_cache``,
``require_csrf``, ``match_param``, ``physical_path``, and
``view_options``.
The meanings of these arguments are the same as the arguments passed to
:meth:`pyramid.config.Configurator.add_view`. If any argument is left
out, its default will be the equivalent ``add_view`` default.
Two additional keyword arguments which will be passed to the
:term:`venusian` ``attach`` function are ``_depth`` and ``_category``.
``_depth`` is provided for people who wish to reuse this class from another
decorator. The default value is ``0`` and should be specified relative to
the ``view_config`` invocation. It will be passed in to the
:term:`venusian` ``attach`` function as the depth of the callstack when
Venusian checks if the decorator is being used in a class or module
context. It's not often used, but it can be useful in this circumstance.
``_category`` sets the decorator category name. It can be useful in
combination with the ``category`` argument of ``scan`` to control which
views should be processed.
See the :py:func:`venusian.attach` function in Venusian for more
information about the ``_depth`` and ``_category`` arguments.
.. seealso::
See also :ref:`mapping_views_using_a_decorator_section` for
details about using :class:`pyramid.view.view_config`.
.. note::
Because of a limitation with ``venusian.Scanner.scan``, note that
``view_config`` will work only for the following conditions.
- In Python packages that have an ``__init__.py`` file in their
directory.
.. seealso::
See also https://github.com/Pylons/venusian/issues/68
- On module top level members.
- On Python source (``.py``) files.
Compiled Python files (``.pyc``, ``.pyo``) without a corresponding
source file are ignored.
.. seealso::
See also the `Venusian documentation
<https://docs.pylonsproject.org/projects/venusian/en/latest/#using-venusian>`_.
"""
venusian = venusian # for testing injection
def __init__(self, **settings):
if 'for_' in settings:
if settings.get('context') is None:
settings['context'] = settings['for_']
self.__dict__.update(settings)
self._get_info()
def _get_info(self):
depth = self.__dict__.get('_depth', 0)
frame = sys._getframe(depth + 2)
frameinfo = inspect.getframeinfo(frame)
sourceline = frameinfo[3][0].strip()
self._info = frameinfo[0], frameinfo[1], frameinfo[2], sourceline
def __call__(self, wrapped):
settings = self.__dict__.copy()
depth = settings.pop('_depth', 0)
category = settings.pop('_category', 'pyramid')
def callback(context, name, ob):
config = context.config.with_package(info.module)
config.add_view(view=ob, **settings)
info = self.venusian.attach(
wrapped, callback, category=category, depth=depth + 1
)
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if settings.get('attr') is None:
settings['attr'] = wrapped.__name__
return wrapped
bfg_view = view_config # bw compat (forever)
def view_defaults(**settings):
"""A class :term:`decorator` which, when applied to a class, will
provide defaults for all view configurations that use the class. This
decorator accepts all the arguments accepted by
:meth:`pyramid.view.view_config`, and each has the same meaning.
See :ref:`view_defaults` for more information.
"""
def wrap(wrapped):
wrapped.__view_defaults__ = settings
return wrapped
return wrap
class AppendSlashNotFoundViewFactory:
"""There can only be one :term:`Not Found view` in any
:app:`Pyramid` application. Even if you use
:func:`pyramid.view.append_slash_notfound_view` as the Not
Found view, :app:`Pyramid` still must generate a ``404 Not
Found`` response when it cannot redirect to a slash-appended URL;
this not found response will be visible to site users.
If you don't care what this 404 response looks like, and you only
need redirections to slash-appended route URLs, you may use the
:func:`pyramid.view.append_slash_notfound_view` object as the
Not Found view. However, if you wish to use a *custom* notfound
view callable when a URL cannot be redirected to a slash-appended
URL, you may wish to use an instance of this class as the Not
Found view, supplying a :term:`view callable` to be used as the
custom notfound view as the first argument to its constructor.
For instance:
.. code-block:: python
from pyramid.httpexceptions import HTTPNotFound
from pyramid.view import AppendSlashNotFoundViewFactory
def notfound_view(context, request): return HTTPNotFound('nope')
custom_append_slash = AppendSlashNotFoundViewFactory(notfound_view)
config.add_view(custom_append_slash, context=HTTPNotFound)
The ``notfound_view`` supplied must adhere to the two-argument
view callable calling convention of ``(context, request)``
(``context`` will be the exception object).
.. deprecated:: 1.3
"""
def __init__(
self, notfound_view=None, redirect_class=HTTPTemporaryRedirect
):
if notfound_view is None:
notfound_view = default_exceptionresponse_view
self.notfound_view = notfound_view
self.redirect_class = redirect_class
def __call__(self, context, request):
path = request.path_info
registry = request.registry
mapper = registry.queryUtility(IRoutesMapper)
if mapper is not None and not path.endswith('/'):
slashpath = path + '/'
for route in mapper.get_routes():
if route.match(slashpath) is not None:
qs = request.query_string
if qs:
qs = '?' + qs
return self.redirect_class(
location=request.path + '/' + qs
)
return self.notfound_view(context, request)
append_slash_notfound_view = AppendSlashNotFoundViewFactory()
append_slash_notfound_view.__doc__ = """\
For behavior like Django's ``APPEND_SLASH=True``, use this view as the
:term:`Not Found view` in your application.
When this view is the Not Found view (indicating that no view was found), and
any routes have been defined in the configuration of your application, if the
value of the ``PATH_INFO`` WSGI environment variable does not already end in
a slash, and if the value of ``PATH_INFO`` *plus* a slash matches any route's
path, do an HTTP redirect to the slash-appended PATH_INFO. Note that this
will *lose* ``POST`` data information (turning it into a GET), so you
shouldn't rely on this to redirect POST requests. Note also that static
routes are not considered when attempting to find a matching route.
Use the :meth:`pyramid.config.Configurator.add_view` method to configure this
view as the Not Found view::
from pyramid.httpexceptions import HTTPNotFound
from pyramid.view import append_slash_notfound_view
config.add_view(append_slash_notfound_view, context=HTTPNotFound)
.. deprecated:: 1.3
"""
class notfound_view_config:
"""
.. versionadded:: 1.3
An analogue of :class:`pyramid.view.view_config` which registers a
:term:`Not Found View` using
:meth:`pyramid.config.Configurator.add_notfound_view`.
The ``notfound_view_config`` constructor accepts most of the same arguments
as the constructor of :class:`pyramid.view.view_config`. It can be used
in the same places, and behaves in largely the same way, except it always
registers a not found exception view instead of a 'normal' view.
Example:
.. code-block:: python
from pyramid.view import notfound_view_config
from pyramid.response import Response
@notfound_view_config()
def notfound(request):
return Response('Not found!', status='404 Not Found')
All arguments except ``append_slash`` have the same meaning as
:meth:`pyramid.view.view_config` and each predicate
argument restricts the set of circumstances under which this notfound
view will be invoked.
If ``append_slash`` is ``True``, when the Not Found View is invoked, and
the current path info does not end in a slash, the notfound logic will
attempt to find a :term:`route` that matches the request's path info
suffixed with a slash. If such a route exists, Pyramid will issue a
redirect to the URL implied by the route; if it does not, Pyramid will
return the result of the view callable provided as ``view``, as normal.
If the argument provided as ``append_slash`` is not a boolean but
instead implements :class:`~pyramid.interfaces.IResponse`, the
append_slash logic will behave as if ``append_slash=True`` was passed,
but the provided class will be used as the response class instead of
the default :class:`~pyramid.httpexceptions.HTTPTemporaryRedirect`
response class when a redirect is performed. For example:
.. code-block:: python
from pyramid.httpexceptions import (
HTTPMovedPermanently,
HTTPNotFound
)
@notfound_view_config(append_slash=HTTPMovedPermanently)
def aview(request):
return HTTPNotFound('not found')
The above means that a redirect to a slash-appended route will be
attempted, but instead of
:class:`~pyramid.httpexceptions.HTTPTemporaryRedirect`
being used, :class:`~pyramid.httpexceptions.HTTPMovedPermanently will
be used` for the redirect response if a slash-appended route is found.
See :ref:`changing_the_notfound_view` for detailed usage information.
.. versionchanged:: 1.9.1
Added the ``_depth`` and ``_category`` arguments.
"""
venusian = venusian
def __init__(self, **settings):
self.__dict__.update(settings)
def __call__(self, wrapped):
settings = self.__dict__.copy()
depth = settings.pop('_depth', 0)
category = settings.pop('_category', 'pyramid')
def callback(context, name, ob):
config = context.config.with_package(info.module)
config.add_notfound_view(view=ob, **settings)
info = self.venusian.attach(
wrapped, callback, category=category, depth=depth + 1
)
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if settings.get('attr') is None:
settings['attr'] = wrapped.__name__
settings['_info'] = info.codeinfo # fbo "action_method"
return wrapped
class forbidden_view_config:
"""
.. versionadded:: 1.3
An analogue of :class:`pyramid.view.view_config` which registers a
:term:`forbidden view` using
:meth:`pyramid.config.Configurator.add_forbidden_view`.
The forbidden_view_config constructor accepts most of the same arguments
as the constructor of :class:`pyramid.view.view_config`. It can be used
in the same places, and behaves in largely the same way, except it always
registers a forbidden exception view instead of a 'normal' view.
Example:
.. code-block:: python
from pyramid.view import forbidden_view_config
from pyramid.response import Response
@forbidden_view_config()
def forbidden(request):
return Response('You are not allowed', status='403 Forbidden')
All arguments passed to this function have the same meaning as
:meth:`pyramid.view.view_config` and each predicate argument restricts
the set of circumstances under which this notfound view will be invoked.
See :ref:`changing_the_forbidden_view` for detailed usage information.
.. versionchanged:: 1.9.1
Added the ``_depth`` and ``_category`` arguments.
"""
venusian = venusian
def __init__(self, **settings):
self.__dict__.update(settings)
def __call__(self, wrapped):
settings = self.__dict__.copy()
depth = settings.pop('_depth', 0)
category = settings.pop('_category', 'pyramid')
def callback(context, name, ob):
config = context.config.with_package(info.module)
config.add_forbidden_view(view=ob, **settings)
info = self.venusian.attach(
wrapped, callback, category=category, depth=depth + 1
)
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if settings.get('attr') is None:
settings['attr'] = wrapped.__name__
settings['_info'] = info.codeinfo # fbo "action_method"
return wrapped
class exception_view_config:
"""
.. versionadded:: 1.8
An analogue of :class:`pyramid.view.view_config` which registers an
:term:`exception view` using
:meth:`pyramid.config.Configurator.add_exception_view`.
The ``exception_view_config`` constructor requires an exception context,
and additionally accepts most of the same arguments as the constructor of
:class:`pyramid.view.view_config`. It can be used in the same places,
and behaves in largely the same way, except it always registers an
exception view instead of a "normal" view that dispatches on the request
:term:`context`.
Example:
.. code-block:: python
from pyramid.view import exception_view_config
from pyramid.response import Response
@exception_view_config(ValueError, renderer='json')
def error_view(request):
return {'error': str(request.exception)}
All arguments passed to this function have the same meaning as
:meth:`pyramid.view.view_config`, and each predicate argument restricts
the set of circumstances under which this exception view will be invoked.
.. versionchanged:: 1.9.1
Added the ``_depth`` and ``_category`` arguments.
"""
venusian = venusian
def __init__(self, *args, **settings):
if 'context' not in settings and len(args) > 0:
exception, args = args[0], args[1:]
settings['context'] = exception
if len(args) > 0:
raise ConfigurationError('unknown positional arguments')
self.__dict__.update(settings)
def __call__(self, wrapped):
settings = self.__dict__.copy()
depth = settings.pop('_depth', 0)
category = settings.pop('_category', 'pyramid')
def callback(context, name, ob):
config = context.config.with_package(info.module)
config.add_exception_view(view=ob, **settings)
info = self.venusian.attach(
wrapped, callback, category=category, depth=depth + 1
)
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' in the settings if one isn't already in there
if settings.get('attr') is None:
settings['attr'] = wrapped.__name__
settings['_info'] = info.codeinfo # fbo "action_method"
return wrapped
def _find_views(
registry,
request_iface,
context_iface,
view_name,
view_types=None,
view_classifier=None,
):
if view_types is None:
view_types = (IView, ISecuredView, IMultiView)
if view_classifier is None:
view_classifier = IViewClassifier
registered = registry.adapters.registered
cache = registry._view_lookup_cache
views = cache.get((request_iface, context_iface, view_name))
if views is None:
views = []
for req_type, ctx_type in itertools.product(
request_iface.__sro__, context_iface.__sro__
):
source_ifaces = (view_classifier, req_type, ctx_type)
for view_type in view_types:
view_callable = registered(
source_ifaces, view_type, name=view_name
)
if view_callable is not None:
views.append(view_callable)
if views:
# do not cache view lookup misses. rationale: dont allow cache to
# grow without bound if somebody tries to hit the site with many
# missing URLs. we could use an LRU cache instead, but then
# purposeful misses by an attacker would just blow out the cache
# anyway. downside: misses will almost always consume more CPU than
# hits in steady state.
with registry._lock:
cache[(request_iface, context_iface, view_name)] = views
return views
def _call_view(
registry,
request,
context,
context_iface,
view_name,
view_types=None,
view_classifier=None,
secure=True,
request_iface=None,
):
if request_iface is None:
request_iface = getattr(request, 'request_iface', IRequest)
view_callables = _find_views(
registry,
request_iface,
context_iface,
view_name,
view_types=view_types,
view_classifier=view_classifier,
)
pme = None
response = None
for view_callable in view_callables:
# look for views that meet the predicate criteria
try:
if not secure:
# the view will have a __call_permissive__ attribute if it's
# secured; otherwise it won't.
view_callable = getattr(
view_callable, '__call_permissive__', view_callable
)
# if this view is secured, it will raise a Forbidden
# appropriately if the executing user does not have the proper
# permission
response = view_callable(context, request)
return response
except PredicateMismatch as _pme:
pme = _pme
if pme is not None:
raise pme
return response
class ViewMethodsMixin:
"""Request methods mixin for BaseRequest having to do with executing
views"""
def invoke_exception_view(
self, exc_info=None, request=None, secure=True, reraise=False
):
"""Executes an exception view related to the request it's called upon.
The arguments it takes are these:
``exc_info``
If provided, should be a 3-tuple in the form provided by
``sys.exc_info()``. If not provided,
``sys.exc_info()`` will be called to obtain the current
interpreter exception information. Default: ``None``.
``request``
If the request to be used is not the same one as the instance that
this method is called upon, it may be passed here. Default:
``None``.
``secure``
If the exception view should not be rendered if the current user
does not have the appropriate permission, this should be ``True``.
Default: ``True``.
``reraise``
A boolean indicating whether the original error should be reraised
if a :term:`response` object could not be created. If ``False``
then an :class:`pyramid.httpexceptions.HTTPNotFound`` exception
will be raised. Default: ``False``.
If a response is generated then ``request.exception`` and
``request.exc_info`` will be left at the values used to render the
response. Otherwise the previous values for ``request.exception`` and
``request.exc_info`` will be restored.
.. versionadded:: 1.7
.. versionchanged:: 1.9
The ``request.exception`` and ``request.exc_info`` properties will
reflect the exception used to render the response where previously
they were reset to the values prior to invoking the method.
Also added the ``reraise`` argument.
"""
if request is None:
request = self
registry = getattr(request, 'registry', None)
if registry is None:
registry = get_current_registry()
if registry is None:
raise RuntimeError("Unable to retrieve registry")
if exc_info is None:
exc_info = sys.exc_info()
exc = exc_info[1]
attrs = request.__dict__
context_iface = providedBy(exc)
# clear old generated request.response, if any; it may
# have been mutated by the view, and its state is not
# sane (e.g. caching headers)
with hide_attrs(request, 'response', 'exc_info', 'exception'):
attrs['exception'] = exc
attrs['exc_info'] = exc_info
# we use .get instead of .__getitem__ below due to
# https://github.com/Pylons/pyramid/issues/700
request_iface = attrs.get('request_iface', IRequest)
manager.push({'request': request, 'registry': registry})
try:
response = _call_view(
registry,
request,
exc,
context_iface,
'',
view_types=None,
view_classifier=IExceptionViewClassifier,
secure=secure,
request_iface=request_iface.combined,
)
except Exception:
if reraise:
reraise_(*exc_info)
raise
finally:
manager.pop()
if response is None:
if reraise:
reraise_(*exc_info)
raise HTTPNotFound
# successful response, overwrite exception/exc_info
attrs['exception'] = exc
attrs['exc_info'] = exc_info
return response