2013-02-14 59 views
5

我正在創建一個使用遍歷的基於金字塔的簡單CMS。有一個叫Collection類,它有一些子類像NewsCollectionGalleriesCollection如果在金字塔中配置了類的視圖,可以使用爲超類設置的視圖嗎?

我需要兩種說法,以顯示這些集合。 frontent,html視圖和後端json視圖(管理面板使用dgrid顯示數據)。後端視圖可以是通用的 - 它在任何情況下都會轉儲json數據。前端視圖不應該 - 每種數據都會有一個自定義模板。

的問題是:當我配置觀點是這樣的:

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

它工作正常。然而,只要我添加任何配置爲NewsCollection視圖優先。即使我將謂詞明確地與上述配置衝突(例如accept='text/html'),仍然不會調用上述視圖。相反,我會得到'謂詞不匹配'。

我的問題是 - 我可以做任何事情使視圖配置爲Collection被調用時,也有NewsCollection的意見?或者我必須使用其他設計(如網址調度或多次添加相同的觀點不同的資源類型)

回答

6

我試圖建立一個非常類似的系統,並發現了同樣的問題 - 事實上,這裏是金字塔bug跟蹤器中的票證:https://github.com/Pylons/pyramid/issues/409

總之,並非所有金字塔中的查看謂詞都相等 - context是一個特例。首先使用context匹配視圖,然後使用其他謂詞縮小選擇範圍。

還有一個最近的pull request這將使金字塔行爲的方式,你(我)會期望 - 但是,從那裏的討論,我看到它不太可能被採納,因爲可能的性能折衷。

UPDATE:拉入請求已經被合併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): 
    .... 
相關問題