From de68d6666305192c6d0ffc8263f7486446a83f73 Mon Sep 17 00:00:00 2001 From: Rob Miller Date: Tue, 28 Dec 2010 18:58:34 -0800 Subject: add decorator argument to add_view method to support auto-wrapping view callables with a decorator at view registration time --- pyramid/config.py | 19 ++++++++++++++++--- pyramid/tests/test_config.py | 13 +++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/pyramid/config.py b/pyramid/config.py index f6b4a2112..083e2a328 100644 --- a/pyramid/config.py +++ b/pyramid/config.py @@ -1008,9 +1008,9 @@ class Configurator(object): def add_view(self, view=None, name="", for_=None, permission=None, request_type=None, route_name=None, request_method=None, request_param=None, containment=None, attr=None, - renderer=None, wrapper=None, xhr=False, accept=None, - header=None, path_info=None, custom_predicates=(), - context=None): + renderer=None, wrapper=None, decorator=None, xhr=False, + accept=None, header=None, path_info=None, + custom_predicates=(), context=None): """ Add a :term:`view configuration` to the current configuration state. Arguments to ``add_view`` are broken down below into *predicate* arguments and *non-predicate* @@ -1119,6 +1119,15 @@ class Configurator(object): view is the same context and request of the inner view. If this attribute is unspecified, no view wrapping is done. + decorator + + A function which will be used to decorate the registered + :term:`view callable`. The decorator function will be + called with the view callable as a single argument, and it + must return a replacement view callable which accepts the + same arguments and returns the same type of values as the + original function. + Predicate Arguments name @@ -1326,6 +1335,10 @@ class Configurator(object): derived_view = self._derive_view(view, permission, predicates, attr, renderer, wrapper, name, accept, order, phash) + if decorator is not None: + wrapped_view = decorator(derived_view) + decorate_view(wrapped_view, derived_view) + derived_view = wrapped_view registered = self.registry.adapters.registered diff --git a/pyramid/tests/test_config.py b/pyramid/tests/test_config.py index c129b21ae..a0bdf95ad 100644 --- a/pyramid/tests/test_config.py +++ b/pyramid/tests/test_config.py @@ -739,6 +739,19 @@ class ConfiguratorTests(unittest.TestCase): result = wrapper(None, None) self.assertEqual(result, 'OK') + def test_add_view_with_decorator(self): + def view(request): + return 'OK' + def view_wrapper(fn): + fn.__assert_wrapped__ = True + return fn + config = self._makeOne(autocommit=True) + config.add_view(view=view, decorator=view_wrapper) + wrapper = self._getViewCallable(config) + self.assertTrue(getattr(wrapper, '__assert_wrapped__', False)) + result = wrapper(None, None) + self.assertEqual(result, 'OK') + def test_add_view_as_instance(self): class AView: def __call__(self, context, request): -- cgit v1.2.3