使用方法名称进行金字塔遍历视图查找 [英] Pyramid traversal view lookup using method names
问题描述
在金字塔中使用遍历 url 查找时,是否可以让视图查找算法检查类的方法名称.例如,我可以这样做:
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
匹配比方说/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
这样 /groups/somegroup/members 和 /groups/somegroup/add 都将解析为各自的类方法吗?
So that both /groups/somegroup/members and /groups/somegroup/add will both resolve to their respective methods of the class?
推荐答案
不能说这是 best
方式(我对金字塔一无所知);但一种选择可能是用一个装饰器来装饰类,该装饰器适当地装饰方法名称.例如.
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
这篇关于使用方法名称进行金字塔遍历视图查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!