2013-01-15 48 views
0

說我有以下看法:打算另一種觀點認爲

def show(request): 
    protect(request) 

    ... some more code here... 

    return render_to_response 
    ... 

「保護」是我導入另一個這樣的應用程序視圖:從watch.actions導入保護

在保護,我做一些檢查,如果條件滿足,我想使用從「保護」的render_to_response權限,並防止返回顯示。如果條件不符合,我想通常返回到「顯示」並繼續執行代碼。

我該怎麼做?

謝謝。

回答

1

如果它的唯一目的是你所描述的,你應該考慮寫作protect作爲視圖裝飾器。 This answer提供了一個如何這樣做的例子。

基於我寫了,你protect裝飾可能類似於圖裝飾:

from functools import wraps 

from django.utils.decorators import available_attrs 

def protect(func): 
    @wraps(func, assigned=available_attrs(func)) 
    def inner(request, *args, **kwargs): 
     if some_condition: 
      return render_to_response('protected_template') 
     return func(request, *args, **kwargs) 
    return inner 

這將讓你再使用它喜歡:

@protect 
def show(request): 
    ... 
    return render_to_response(...) 
+0

感謝乾淨的解決方案。 –