Hello all,

I recently made a little code snippet that has come in very handy for
my Pylon projects. It automatically connects methods in a controller
with a url. For example, if we have a controller called MyController,
and inside it a method:

def myaction(self, arg1, arg2)

The, on our make_map, calling:

add_magic_route(map, MyController)

will automatically insert /my/myaction/{arg1}/{arg2} into the map and
associate with the correct method in the controller. Note that it
works better calling it before any custom routes. I hope this will be
useful to someone.

=============
Here is the code:
=============

from types import FunctionType
import inspect

def add_magic_route(map_instance, clazz, controller_name=None,
ignore_actions=None):

    if ignore_actions is None:
        ignore_actions = []

    # identifies the controller name
    if controller_name is None:
        name = clazz.__name__
        pos = name.find("Controller")
        if pos < 0:
            controller_name = name.lower()
        else:
            controller_name = name.lower()[:pos]

    # puts all the controller methods on the map
    for method_name, method in clazz.__dict__.items():
        if type(method) == FunctionType \
        and method_name[0] != "_" \
        and method_name not in ignore_actions:
            args = inspect.getargspec(method).args
            args = map(lambda x: '{'+x+'}',args[1:])
            if len(args):
                map_instance.connect(
                            '/'+controller_name+
                            '/'+method_name+
                            '/'+'/'.join(args),
 
controller=controller_name,action=method_name)
                print '/'+controller_name+'/'+method_name
+'/'+'/'.join(args)

-- 
You received this message because you are subscribed to the Google Groups 
"pylons-devel" group.
To post to this group, send email to pylons-devel@googlegroups.com.
To unsubscribe from this group, send email to 
pylons-devel+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/pylons-devel?hl=en.

Reply via email to