test_func和view_func在Python/Django中做什么?

test_func和view_func在Python/Django中做什么?,python,django,Python,Django,我试图分解Django中的以下代码,以了解它在做什么,并在必要时对其进行编辑,但我无法完全了解其中一些函数在做什么,或者它们来自何处 test_func和view_func Django是特定的还是这些内置python函数 结论: 我不确定我是如何/为什么忽略了这样一个事实,即这些只是被定义为函数的参数。我需要开始更加关注细节 下面是我试图分解/理解的Django函数: def user_passes_test(test_func, login_url=None, redirect_field_

我试图分解Django中的以下代码,以了解它在做什么,并在必要时对其进行编辑,但我无法完全了解其中一些函数在做什么,或者它们来自何处

test_func和view_func Django是特定的还是这些内置python函数

结论: 我不确定我是如何/为什么忽略了这样一个事实,即这些只是被定义为函数的参数。我需要开始更加关注细节

下面是我试图分解/理解的Django函数:

def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            print test_func
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse.urlparse(login_url or
                                                        settings.LOGIN_URL)[:2]
            current_scheme, current_netloc = urlparse.urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, login_url, redirect_field_name)
        return _wrapped_view
    return decorator

test_func
view_func
是作为参数传入的函数——也就是说,这些名称只是任意变量名称。是一个应用于视图(成为变量
view\u func
)——它作为参数(
test\u func
)传递一个函数,该函数接受
用户
,并返回
True
False

view\u func
是一个变量
test_func
是一个“检查用户是否通过给定测试”的函数

因此,您编写了一个函数,该函数向用户请求某些内容,如果通过,则返回
True
。然后将该函数传递给
user\u passes\u test
,它创建了一个装饰器,您可以使用它在用户看到您的视图之前首先测试用户,如下所示:

@user_passes_test
def test_intelligence(user):
    if is_intelligent:
        return True
    else:
        return False

@test_intelligence
def my_view(request):
    #this is the view you only want intelligent people to see
    pass

文档中提到了装饰器
wrapps
是一个装饰程序,它在装饰过程中保留被包装函数的签名(名称、参数等)。它的位置。

我的另一个回答是:哇,我不知道为什么我想得那么多。。我一直在想,出于某种原因,它们是在python函数中构建的。。基本上,我只是想弄清楚它们在这个特殊情况下是如何被使用的。我假设decorator是以某种方式自动调用的,因为当用户通过对其调用的测试()时,在中没有对它的直接调用。。我只是注意到“returndecorator”出于某种原因认为它在函数内部。我需要更加注意细节。。我再把每一个都读一遍,看看哪一个更好地回答了这个问题