0

假设我有以下观点:

def show(request):
    protect(request)

    ... some more code here...

    return render_to_response
    ...

“保护”是我正在导入的另一个应用程序视图: from watch.actions import protect

在保护中,我进行了一些检查,如果满足条件,我想从“保护”中直接使用 render_to_response 并防止返回显示。如果不满足条件,我想正常返回“显示”并继续执行代码。

我该怎么做?

谢谢。

4

1 回答 1

1

如果它的唯一目的是您所描述的,您应该考虑将其编写protect为视图装饰器。这个答案提供了一个如何做到这一点的例子。

根据我写的视图装饰器,你的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(...)
于 2013-01-15T00:25:13.130 回答