quick search:
 

Zope Principles Part 3 - Traversal

Submitted by: runyaga
Last Edited: 2002-09-14

Category: Python(Script)

Average rating is: 0.0 out of 5 (0 ratings)

Description:
The ZODB is a heirarchy. It may look like a filesystem
but you dont traverse it (change folders) using traditional
'cd' commands. When you want to move around in the ZODB
you have a number of options. It boils down to 'context',
'containment' and 'traversal'. Common terms you've heard
over and over again if you've read any Zope documentation.

This recipe demonstrates traversal.


Source (Text):
#create a Script(Python)
#path takes a tuple i.e. ('', 'QuickStart')
#id: doTraversal1
#parameters: path, obj=None
if obj is None:
    obj=context
target=obj.restrictedTraverse(path)
print target.absolute_url(), ' is the absolute url (virtual host aware)'
print target.getPhysicalPath(), ' is the physical path in ZODB from root'
print target.title_or_id(), ' prints the title or id of the object'
return printed

#id: doTraversal2
#parameters: path, obj=None
if obj is None:
    obj=context
for elem in path:
    if elem:
        print 'traversing to ', elem
        obj=getattr(obj, elem)
print obj.absolute_url(), ' is the absolute url (virtual host aware)'
print obj.getPhysicalPath(), ' is the physical path in ZODB from root'
print obj.title_or_id(), ' prints the title or id of the object'
return printed

Explanation:
you can use any of these by creating another script
and calling these i.e.

return context.doTraversal( ('', 'QuickStart', 'Outline'), context)

doTraversal - restrictedTraverse()
given a path of ids, Zope will use the obj (or context) and
attempt to traverse the sequence of ids. it will return back
the object found.

#doTraversal2 shows off getattr()
getattr() is the most common way of dynamically getting attributes
from Python objects. getattr/hasattr are the most important
bits of Zen you need to master ZODB. Basically we are simulating
restrictedTraverse by iterating over the path of ids and calling
getattr() on the result.


Comments:

No Comments