Pyramid traversal view lookup using method names

萝らか妹 提交于 2019-12-02 08:09:03

问题


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:


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


来源:https://stackoverflow.com/questions/14076046/pyramid-traversal-view-lookup-using-method-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!