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

Chr*_*ris 5 python django

我试图在 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
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 5

view_func是一个Django 视图test_func是一个“检查用户是否通过给定测试”的函数。

因此,您编写一个函数,向用户请求某些信息,True如果通过则返回。然后,您将该函数传递给它user_passes_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
Run Code Online (Sandbox Code Playgroud)

文档中的函数定义下提到了装饰器。wraps是一个装饰器,它通过装饰过程保留被包装函数的签名(名称、参数等)。它位于functools 中