【问题标题】:Can a view configured for superclass be used if a view for a class was configured in Pyramid?如果在 Pyramid 中配置了类的视图,是否可以使用为超类配置的视图?
【发布时间】:2013-04-05 06:08:06
【问题描述】:

我正在创建一个使用遍历的简单的基于金字塔的 CMS。有一个名为Collection 的类,它有一些子类,如NewsCollectionGalleriesCollection 等。

我需要两种视图来显示这些集合。前端,html 视图和后端,json 视图(管理面板使用 dgrid 显示数据)。后端视图可以是通用的——它在每种情况下都转储 json 数据。前端视图不应该 - 每种数据都有一个自定义模板。

问题是:当我这样配置视图时:

@view_config(context=Collection, xhr=True, renderer='json', accept='application/json')

它工作正常。但是,一旦我添加为NewsCollection 配置的 any 视图,此视图优先。即使我专门放置谓词与上述配置冲突(例如accept='text/html'),仍然不会调用上述视图。相反,我会得到一个“谓词不匹配”。

我的问题是 - 当 NewsCollection 也有视图时,我可以做些什么来调用为 Collection 配置的视图吗?还是我必须使用其他设计(如 url dispatch 或为不同的资源类型多次添加相同的视图)

【问题讨论】:

    标签: python inheritance pyramid


    【解决方案1】:

    我尝试构建一个非常相似的系统并发现了同样的问题 - 事实上,这是 Pyramid 错误跟踪器中的票证:https://github.com/Pylons/pyramid/issues/409

    简而言之,并非所有 Pyramid 中的视图谓词都是相等的 - context 是一种特殊情况。首先使用context 匹配视图,然后使用其他谓词缩小选择范围。

    还有一个最近的pull request 可以让 Pyramid 以您(和我)期望的方式运行 - 但是,从那里的讨论中,我发现它不太可能被采用,因为可能会进行性能权衡。

    更新:拉取请求已于 2013 年 3 月合并,所以我想它应该在 1.4 之后的版本中可用)

    一种解决方法是使用自定义谓词:

    def context_implements(*types):
        """
        A custom predicate to implement matching views to resources which
        implement more than one interface - in this situation Pyramid has
        trouble matching views to the second registered interface. See
        https://github.com/Pylons/pyramid/issues/409#issuecomment-3578518
    
        Accepts a list of interfaces - if ANY of them are implemented the function
        returns True
        """
        def inner(context, request):
            for typ in types:
                if typ.providedBy(context):
                    return True
            return False
        return inner
    
    
    @view_config(context=ICollection,
        custom_predicates=(context_implements(INewsCollection),)
        )
    def news_collection_view(context, request):
        ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2011-03-05
      • 1970-01-01
      相关资源
      最近更新 更多