Far*_*ggs 6 python traversal url-routing dom-traversal pyramid
在Traversal金字塔应用程序中,如何处理__name__
与视图名称匹配的资源?
如果我想进入资源的视图可调用"视图",我将使用如下的URL路径:/foo/bar/view
.它遍历resource_tree,如下所示:
RootFactory(request) => RootFactory
RootFactory['foo'] => Foo
Foo['bar'] => Bar
Bar['view'] => KeyError
Run Code Online (Sandbox Code Playgroud)
...并且因为它无法遍历Bar&'view',所以它假定'view'是视图名称,并匹配我的视图可调用
@view_config(name='view')
def view(context, request):
return Response(context.__name__)
Run Code Online (Sandbox Code Playgroud)
获取我使用的路径的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
Run Code Online (Sandbox Code Playgroud)
理想情况下,在这种情况下,/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
Run Code Online (Sandbox Code Playgroud)
该问题提到想要生成可调用标题视图的资源 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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
161 次 |
最近记录: |