2013-01-15 40 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

感谢干净的解决方案。 –