Search code examples
pythonwebpyramidpylons

Ensuring every view in Pyramid app is decorated with custom decorator


Per http://pyramid-cookbook.readthedocs.org/en/latest/views/chaining_decorators.html I can decorate a Pyramid view:

@view_config(decorator=a_special_decorator, renderer='json')
def myview(request):
    return {'a':1}

OK but I need to ensure that every view in Pyramid app is decorated with a_special_decorator. Is there a way of ensuring, either in live app or in test phase, that it is so?


Solution

  • I think the better approach would be: Use a class based views and inherit all your views from the same base class that has the facilities you are trying to add.

    However if you want to decorate all your views in your application the approach would be following

    • Create a scan() method which takes Python module as input and reads through, a bit similar to Pyramid's own scan

    • If your scan() finds a view function signature, it decorates the function and replaces the original function in the module in-place

    • Call your custom scan before letter Pyramid itself scan the module, so that Pyramid will pick up "fixed" functions