我如何在Django中编写装饰器以检查两个单独的条件并进行相应的重定向?

在我的项目中,注册后,用户必须先创建配置文件,然后才能访问网站的其余部分.我想要一个装饰器@profile_decorator来代替@login_decorator.

如果用户是

>未登录,重定向到登录URL
>已登录,但没有个人资料,请重定向以创建个人资料网址
>已登录,具有配置文件,允许继续查看

这是来自django.contrib.auth.decorators的:

from functools import wraps

from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.shortcuts import resolve_url
from django.utils.decorators import available_attrs
from django.utils.six.moves.urllib.parse import urlparse


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()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # 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(resolved_login_url)[:2]
            current_scheme, current_netloc = 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, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator


def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_authenticated(),
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

这是我到目前为止的内容:

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test

from django.conf.settings import CREATE_PROFILE_REDIRECT_URL

from .models import Profile


def profile_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in and has created
    a profile, redirecting to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        test_func,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator


def test_func(u):
    if u.is_authenticated():
        if Profile.objects.filter(user=u).exists():
            return True
    return False

现在我只是感到困惑,意识到我不知道如何使它对1.和2.有不同的反应.

编辑:login_required装饰器具有我想保留的其他功能-成功登录后,它将用户重定向回他们尝试访问的原始页面.对不起,应该说从开始.

解决方法:

我认为您无法通过尝试使用user_passes_test装饰器来帮助自己.如果您从头开始创建装饰器,则会发现这容易得多.

def profile_required(view_func):
    def wrapped(request, *args, **kwargs):
        if request.user.is_anonymous():
            path = request.build_absolute_uri()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, LOGIN_URL)
        else:
            try:
                profile = request.user.profile
            except Profile.DoesNotExist:
                return redirect(CREATE_PROFILE_REDIRECT_URL)
            else:
                return view_func(request, *args, **kwargs)
    return wrapped
上一篇:Scala中的Python样式装饰器


下一篇:我们可以使用装饰器设计任何函数吗?