Decorating a Pyramid view function
Imagine you have some view functions in Pyramid and want to decorate them with your decorator, something like this:
|
|
Notice the difference in the signatures of the two functions.
In the first one we pass only the request argument while in the second one we pass both the context and request arguments.
From Pyramid docs:
Usually view callables are defined to accept only a single argument: request. However, a view callable may alternately be defined as any class, function, or callable that accepts two positional arguments: a context resource as the first argument and a request as the second argument.
Using pure Python
|
|
There is one caveat though, notice the if/else statement.
We need to inspect the signature of the view function to determine if it uses either both the context and the request arguments or only the request argument.
Of course Pyramid provides ways to decorate a view function without the need of inspecting it.
Using the decorator keyword argument when configuring the view
|
|
..and of course removing the inspection code as there is no need for it any more but we need to accept in the wrapper both the context and request as well as passing them again when we call the view:
|
|
Dropping in python’s pdb built-in module just before we return the call of the view function we see that we wrap a function called:
render_view.<locals>.viewresult_to_response
|
|
Wait, this is not any of our functions!
The reason for defining the wrapper with both arguments context, request, is that we do not wrap the actual view function but something earlier in the process of calling the actual view. That makes sense because something has to do the inspection before calling the actual view and this is not us but Pyramid of course.
Doing the same with the pure python way we get:
<function get_users at 0x7f5a9e452ea0>, which is the actual view function.
More on decorators.
There is also a third way, by creating a custom Pyramid view deriver
A view deriver avoids the need of importing the decorator in places that needs to be used and makes it more declarative.
|
|
Again we have to pass both context and request, Pyramid will pass only the needed arguments, so no need for inspecting the function.
|
|
More on view derivers.
Big thanks to raydeo and the rest of the #pyramid members who are always helpful!