Using Traversal in Pyramid Views¶
A trivial example of how to use traversal in your view code.
You may remember that a Pyramid view is called with a context argument.
def my_view(context, request):
return render_view_to_response(context, request)
When using traversal, context
will be the resource object
that was found by traversal. Configuring which resources a view
responds to can be done easily via either the @view.config
decorator.
1from models import MyResource
2
3@view_config(context=MyResource)
4def my_view(context, request):
5 return render_view_to_response(context, request)
or via config.add_view
:
from models import MyResource
config = Configurator()
config.add_view('myapp.views.my_view', context=MyResource)
Either way, any request that triggers traversal and traverses to a
MyResource
instance will result in calling this view with that
instance as the context
argument.
Optional: Using Interfaces¶
If your resource classes implement interfaces, you can configure your views by interface. This is one way to decouple view code from a specific resource implementation.
1# models.py
2from zope.interface import implements
3from zope.interface import Interface
4
5class IMyResource(Interface):
6 pass
7
8class MyResource(object):
9 implements(IMyResource)
10
11# views.py
12from models import IMyResource
13
14@view_config(context=IMyResource)
15def my_view(context, request):
16 return render_view_to_response(context, request)
See Also¶
The "Virginia" sample application: https://github.com/Pylons/virginia/blob/master/virginia/views.py
ZODB and Traversal in Pyramid tutorial: https://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/wiki/index.html#bfg-wiki-tutorial
Resources which implement interfaces: https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/resources.html#resources-which-implement-interfaces