2012-07-17 56 views
2

後備視圖考慮下面的金字塔應用:定義在遍歷

from pyramid.config import Configurator 

class Foo(dict): 
    pass 

def make_root(request): 
    return {'foo': Foo()} 

def foo(request): 
    return request.subpath 

def bar(request): 
    return {"whoami": "bar", "subpath": request.subpath} 

def start(global_config, **settings): 
    config = Configurator(settings=settings) 
    config.set_root_factory(make_root) 
    config.add_view(foo, context=Foo, renderer="json") 
    config.add_view(bar, name="bar", context=Foo, renderer="json") 
    return config.make_wsgi_app() 

此應用程序使用穿越和響應/foo/foo/bar就好了。我在想,如果,遍歷/foo/booarns的時候,有一些地方在穿越之前決定返回一個404像一個默認掛鉤,或後備觀點:

config.add_view(any_other, name="*default*", context=Foo, ...) 

然後,這一觀點將被調用時路徑的第二個組件尚未綁定到任何其他視圖,但在相同的上下文中,路徑組件仍可用爲request.view_namerequest.subpath

回答

4

我認爲containment謂詞仍然會在這裏工作。

@notfound_view_config(containment=Foo) 
def notfound(request): 
    return HTTPNotFound('no views for Foo detected for view %s' % request.view_name) 
+0

確實。它從來沒有發生過,因爲它很好地隱藏在API參考中。非常感謝。 – C2H5OH 2012-07-17 20:35:59

0

According to the docs,你只需要指定一個空字符串名稱:

config.add_view(any_other, name="", context=Foo, ...) 
+0

這是行不通的,已經試過了。 – C2H5OH 2012-07-17 15:43:16

0

當金字塔是無法映射URL查看代碼,它會觸發一個「找不到視圖」。默認「找不到視圖」可以通過應用程序配置使用以下覆蓋:

from pyramid.view import notfound_view_config 

@notfound_view_config() 
def notfound(request): 
    return Response('Not Found, dude', status='404 Not Found') 

def main(globals, **settings): 
    config = Configurator() 
    config.scan() 
+0

但是如果我想針對不同的情況單獨做這件事,我必須派遣自己,對吧? – C2H5OH 2012-07-17 15:44:23

+0

任何時候收到內部的NotFound響應都會觸發'notfound_view_config()'裝飾器。 – RobB 2012-07-17 15:49:18