我想在每次請求前檢查一個條件並調用不同的視圖。 這是如何實現的?如何添加條件重定向到金字塔中的每個視圖?
一個解決方案,我能想到的是添加一些到用戶NewRequest,但我堅持:
@subscriber(NewRequest)
def new_request_subscriber(event):
if condition:
#what now?
我想在每次請求前檢查一個條件並調用不同的視圖。 這是如何實現的?如何添加條件重定向到金字塔中的每個視圖?
一個解決方案,我能想到的是添加一些到用戶NewRequest,但我堅持:
@subscriber(NewRequest)
def new_request_subscriber(event):
if condition:
#what now?
@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
你給好關於「條件」的信息非常少,或者您稱之爲「調用不同視圖」的含義,因此我假定您不想調用重定向,而是希望應用程序認爲正在請求不同的URL。要做到這一點,您可以查看pyramid_rewrite
,這對於這些事情來說非常方便,或者您可以在NewRequest
訂戶內更改請求的路徑,因爲它在金字塔派送到視圖之前被調用。
if request.path == '/foo':
request.path = '/bar':
config.add_route('foo', '/foo') # never matches
config.add_route('bar', '/bar')
假設我想總是顯示(對於任何URL)sign_in網頁,如果用戶是SIGN_OUT Request的不modifible bacuase我得到: *** AttributeError錯誤:無法設置屬性 – xliiv 2012-04-27 16:39:15
對不起它的'request.path_info ',更新的答案。您可以用這種方式顯示頁面,但在這種情況下,您可能想使用@raj顯示的'raise HTTPFound'方法重定向,或者使用Pyramid的認證系統自動處理它。 – 2012-04-27 19:15:03
我認爲@Raj解決方案對我來說是最好的選擇。謝謝大家。 – xliiv 2012-04-28 13:29:09
另一個選項,「檢查情況......,並呼籲不同的看法」是使用自定義視圖謂詞
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。
很酷的東西,我不知道,我學到了很多,這不是完美的解決方案,因爲我不得不改變我的所有意見,但謝謝。 :) – xliiv 2012-04-28 13:27:51
這應該是'raise',你不能從訂閱者返回任何東西。 – 2012-04-27 19:15:22