我想在每个请求之前检查一个条件并调用不同的视图。 这是如何实现的?
我能想到的一个解决方案是向订户NewRequest添加一些内容,但我被困住了:
@subscriber(NewRequest)
def new_request_subscriber(event):
if condition:
#what now?
答案 0 :(得分:3)
@subscriber(NewRequest)
def new_request_subscriber(event):
if condition:
raise pyramid.httpexceptions.HTTPFound(location=somelocation) ## to issue a proper redirect
更多信息可以在这里找到: http://pyramid.readthedocs.org/en/latest/api/httpexceptions.html#pyramid.httpexceptions.HTTPFound
答案 1 :(得分:1)
嗯,你提供的关于“条件”的信息很少,或者说“调用不同的视图”是什么意思,所以我假设你不想调用重定向但是你希望应用程序认为不同正在请求URL。为此,您可以查看pyramid_rewrite
,这对于这些事情非常方便,或者您可以在NewRequest
订阅者中更改请求的路径,因为它在Pyramid调度到视图之前被调用。 / p>
if request.path == '/foo':
request.path = '/bar':
config.add_route('foo', '/foo') # never matches
config.add_route('bar', '/bar')
答案 2 :(得分:1)
“检查条件......并调用不同视图”的另一个选项是使用自定义视图谓词
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,它将显示一个登录表单。