Pyramid Traversal __name__匹配视图名称
问题描述:
在Traversal金字塔应用程序中,如何处理与视图名称匹配的资源(__name__
)?Pyramid Traversal __name__匹配视图名称
如果我想要查看一个资源的视图可调用的“视图”,我会使用一个URL路径,如:/foo/bar/view
。它穿越resource_tree像这样:
RootFactory(request) => RootFactory
RootFactory['foo'] => Foo
Foo['bar'] => Bar
Bar['view'] => KeyError
...因为它无法穿越过去吧&“视图”遗留下来的,它假定“观看”是视图名称,并匹配我的看法可调用
@view_config(name='view')
def view(context, request):
return Response(context.__name__)
要获得该路径的URL,我会使用request.resource_url(resource, "view"
)。
但是,如果我有一个资源,例如Bar.__name__ = "view"
,如何解析Foo上的“查看”URL?
# path: /foo/view
RootFactory(request) => RootFactory
RootFactory['foo'] => Foo # ideally stop here with view_name="view"
Foo['view'] => Bar.__name__ = "view"
# all parts of path matched so view_name="" and context=Bar
理想的情况下,在这种情况下,/foo/view
将指向view(Foo, request)
,并/foo/view/view
将指向view(Bar, request)
哪里Bar.__name__ == "view"
。
有没有办法处理这个问题,而不写入检测__name__
和视图名称之间的冲突?
答
我最终解决的方案是添加一个任意层的容器资源。
下面是资源的示例结构:
class Foo(object):
def __init__(self, parent, name):
self.__parent__ = parent
self.__name__ = name
def __getitem__(self, key):
if key == "bar":
return BarContainer(self, "bar")
else:
raise KeyError()
class BarContainer(object):
def __init__(self, parent, name):
self.__parent__ = parent
self.__name__ = name
def __getitem__(self, key):
return Bar(self, key)
class Bar(object):
def __init__(self, parent, name):
self.__parent__ = parent
self.__name__ = name
问题提到想要生成资源URL到视图可调用标题视图。与BarContainer
这只是增加了一个额外的斜线:
/{foo}/bar/{bar}/<view_name>
/a/view => view(context=Foo(name='a'), request)
/a/bar/view => view(context=BarContainer(name='bar'), request)
/a/bar/b/view => view(context=Bar(name='b'), request)