On Feb 20, 11:06 pm, Matthew Bevan <[EMAIL PROTECTED]> wrote:
[snip]
> Investigate the cherrypy._cputil.get_object_trail() function.
> It took me quite awhile to figure out how it works, as the few
> examples I've seen online are pretty obfuscated.

I agree it is a little obfuscated.

However, this gives you the current object trail, for the url path you
are currently on. If you wanted an arbitrary instance of a specific
class, AFAIK, you need to search the root tree yourself.

I wrote something along those lines myself today. I wanted to build an
automatic menu from all the connected objects/methods on a cherrypy
tree, and a widget to display it. I parsed the cherrypy object tree at
start-up and collected the names of classes/methods to use for
displaying the widget. Below is an untested attempt to use the same
approach to searching the cherrypy tree, but to achieve the original
posters goal.

from inspect import getmembers

def parse_instance_dict(obj, path=[]):
    instances = { obj.__class__ : path }
    for name, value in getmembers(obj):
        if isinstance(value, controllers.Controller):
            instances.update(**parse_instance_dict(value, path +
[name]))
    return instances

To use:

instance_of = dict()

class Root(controllers.RootController):
    def __init__(self):
        global instance_of
        instance_of = parse_instance_dict(self) # can only parse the
tree once its been created!

class MyController(controllers.Controller):
    ....

class MyOtherController(controllers.Controller):

    def some_method(self, *args, **kwds):
         ....
         if some_condition:
             redirect(instance_of[MyController])


This will build a lookup table based on class name, which would work
as long as you don't have two instances of the same class :) You could
add an id attribute or similar to the controller instances simply
enough, and use that as your lookup key, which would be more robust.
This way you can move your tree around at will and this will
automatically pickup the changes. Not sure if this is the best way to
parse a cherrypy tree, but this approach is working nicely for me with
my auto-menu widget.

HTH

--
wavy davy


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to