Pyramid traversal view lookup using method names

2019-03-02 05:05发布

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?

1条回答
Anthone
2楼-- · 2019-03-02 05:32

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
查看更多
登录 后发表回答