2012-04-27 49 views
1

我想在每次请求前检查一个条件并调用不同的视图。 这是如何实现的?如何添加条件重定向到金字塔中的每个视图?

一个解决方案,我能想到的是添加一些到用户NewRequest,但我坚持:

@subscriber(NewRequest) 
def new_request_subscriber(event): 
    if condition: 
    #what now? 

回答

1

你给好关于“条件”的信息非常少,或者您称之为“调用不同视图”的含义,因此我假定您不想调用重定向,而是希望应用程序认为正在请求不同的URL。要做到这一点,您可以查看pyramid_rewrite,这对于这些事情来说非常方便,或者您可以在NewRequest订户内更改请求的路径,因为它在金字塔派送到视图之前被调用。

if request.path == '/foo': 
    request.path = '/bar': 

config.add_route('foo', '/foo') # never matches 
config.add_route('bar', '/bar') 
+0

假设我想总是显示(对于任何URL)sign_in网页,如果用户是SIGN_OUT Request的不modifible bacuase我得到: *** AttributeError错误:无法设置属性 – xliiv 2012-04-27 16:39:15

+0

对不起它的'request.path_info ',更新的答案。您可以用这种方式显示页面,但在这种情况下,您可能想使用@raj显示的'raise HTTPFound'方法重定向,或者使用Pyramid的认证系统自动处理它。 – 2012-04-27 19:15:03

+0

我认为@Raj解决方案对我来说是最好的选择。谢谢大家。 – xliiv 2012-04-28 13:29:09

1

另一个选项,“检查情况......,并呼吁不同的看法”是使用自定义视图谓词

Cris McDonough's blog post

def example_dot_com_host(info, request): 
     if request.host == 'www.example.com: 
      return True 

这是一个自定义的断言那里。如果主机名是www.example.com,则返回True。下面是我们如何使用它:

@view_config(route_name='blogentry', request_method='GET') 
    def get_blogentry(request): 
     ... 

    @view_config(route_name='blogentry', request_method='POST') 
    def post_blogentry(request): 
     ... 

    @view_config(route_name='blogentry', request_method='GET', 
       custom_predicates=(example_dot_com_host,)) 
    def get_blogentry_example_com(request): 
     ... 

    @view_config(route_name='blogentry', request_method='POST', 
       custom_predicates=(example_dot_com_host,)) 
    def post_blogentry_example_com(request): 
     ... 

然而,对于您的特定问题(显示在页面的标志,如果用户没有权限查看的页面)更好的方式来实现,这将是set up permissions的意见,使框架当用户没有权限时引发异常,然后注册将在窗体中显示签名的custom view for that exception

+0

很酷的东西,我不知道,我学到了很多,这不是完美的解决方案,因为我不得不改变我的所有意见,但谢谢。 :) – xliiv 2012-04-28 13:27:51