我正在使用django user_passes_test decorator检查用户权限。

@user_passes_test(lambda u: has_add_permission(u, "project"))
def create_project(request):
......

我正在调用一个回调函数,它具有带两个参数user和一个字符串的\添加\权限。我想将请求对象与它一起传递,这是可能的吗?另外,有谁能告诉我我们如何能够直接访问decorator内部的用户对象吗?

最佳答案

不,您不能将请求传递给user_passes_test。要了解其工作原理和原因,只需前往:

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):
            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

这是装饰器后面的代码。如您所见,传递给decorator的测试函数(在您的例子中,user_passes_test)只传递一个参数,lambda u: has_add_permission(u, "project")。现在,当然可以编写自己的decorator(甚至直接复制此代码并对其进行修改)来传递request.user本身,但不能使用默认的request实现。

关于python - 如何在user_passes_test装饰器可调用函数中传递Django请求对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11872560/

10-11 22:20
查看更多