【问题标题】:Pyramid Traversal __name__ matching a view namePyramid Traversal __name__ 匹配视图名称
【发布时间】:2016-05-13 20:07:40
【问题描述】:

在遍历金字塔应用程序中,如何处理带有与视图名称匹配的__name__ 的资源?

如果我想访问资源的视图可调用“视图”,我会使用如下 URL 路径:/foo/bar/view。它像这样遍历resource_tree:

RootFactory(request) => RootFactory
RootFactory['foo']   => Foo
Foo['bar']           => Bar
Bar['view']          => KeyError

...因为它无法遍历 Bar 并且留下了“视图”,它假定“视图”是视图名称,并且与我的可调用视图匹配

@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__ 和视图名称之间的冲突的情况下处理这个问题?

【问题讨论】:

    标签: python url-routing pyramid traversal dom-traversal


    【解决方案1】:

    我最终得到的解决方案是添加任意层的容器资源。

    以下是资源的示例结构:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2021-11-06
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      相关资源
      最近更新 更多