1

In pyramid when using traversal url lookup, is it possible to have the view lookup algorithm check for method names of a class. For example, I could do something like this:

@view_defaults(context=models.Group)
class GroupView(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    @view_config(name='members')
    def members(self):
        pass

to match let's say /groups/somegroup/members

Is there a way to make the name lookup part dynamic? That is, something like this:

@view_defaults(context=models.Group)
class GroupView(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def members(self):
        pass

    def add(self):
        pass

So that both /groups/somegroup/members and /groups/somegroup/add will both resolve to their respective methods of the class?

Falmarri
  • 47,727
  • 41
  • 151
  • 191
  • You'll have to do this yourself. Don't forget that the view definitions are there not just to map the URL to a method but also to specify predicates and rendering options. You're going to lose all of that cool stuff on a per-view basis when you framework it out. – Michael Merickel Dec 29 '12 at 01:10

1 Answers1

3

Can't say this is the best way (I don't know anything about pyramid); but one option might be to just decorate the class with a decorator that decorates the method names appropriately. eg.

import inspect

def config_wrap(func, name):
    @view_config(name=name)
    def wrapped(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapped

def dynamic_names(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls,name,config_wrap(m, name))
    return cls


@dynamic_names
@view_defaults(context=models.Group)
class GroupView(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request

    def members(self):
        pass

    def add(self):
        pass
Gerrat
  • 28,863
  • 9
  • 73
  • 101