2024-10-05 14:25:45 发布
网友
我想在每次请求之前检查一个条件并调用不同的视图。 这是如何实现的?在
我能想到的一个解决方案是向subscriber NewRequest添加一些内容,但我遇到了问题:
@subscriber(NewRequest) def new_request_subscriber(event): if condition: #what now?
关于“条件”或“调用不同视图”的含义,您所给出的信息很少,所以我假设您不想调用重定向,而是希望应用程序认为请求的是不同的URL。要做到这一点,您可以查看pyramid_rewrite,这对这些事情非常方便,或者您也可以在NewRequest订阅服务器中更改请求的路径,因为它是在金字塔向视图发送之前调用的。在
pyramid_rewrite
NewRequest
if request.path == '/foo': request.path = '/bar': config.add_route('foo', '/foo') # never matches config.add_route('bar', '/bar')
@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
另一个选择是“检查条件。。。“和调用不同的视图”是指使用自定义视图谓词
来自Cris McDonough's blog post:
def example_dot_com_host(info, request): if request.host == 'www.example.com: return True
这是一个自定义谓词。如果主机名为www.example.com。下面是我们如何使用它:
但是,对于您的特定问题(如果用户没有查看页面的权限,则显示登录页面),更好的方法是对视图使用set up permissions,这样当用户没有权限时,框架会引发一个异常,然后注册一个custom view for that exception,它将显示登录表单。在
关于“条件”或“调用不同视图”的含义,您所给出的信息很少,所以我假设您不想调用重定向,而是希望应用程序认为请求的是不同的URL。要做到这一点,您可以查看
pyramid_rewrite
,这对这些事情非常方便,或者您也可以在NewRequest
订阅服务器中更改请求的路径,因为它是在金字塔向视图发送之前调用的。在更多信息请访问: http://pyramid.readthedocs.org/en/latest/api/httpexceptions.html#pyramid.httpexceptions.HTTPFound
另一个选择是“检查条件。。。“和调用不同的视图”是指使用自定义视图谓词
来自Cris McDonough's blog post:
这是一个自定义谓词。如果主机名为www.example.com。下面是我们如何使用它:
^{pr2}$但是,对于您的特定问题(如果用户没有查看页面的权限,则显示登录页面),更好的方法是对视图使用set up permissions,这样当用户没有权限时,框架会引发一个异常,然后注册一个custom view for that exception,它将显示登录表单。在
相关问题 更多 >
编程相关推荐