区分自定义装饰器中未经身份验证的用户

时间:2017-07-26 11:42:24

标签: python django

Django初学者在这里。

我一直在使用内置的login_required装饰器。我想覆盖某些推荐网址与特定模式匹配的用户(例如,所有来自/buy_and_sell/的用户)。

我的目的是为这些用户显示一个特殊的登录页面,并为其他人显示一个通用页面。

我一直在研究编写自定义装饰器的各种示例(例如herehereherehere)。但我发现初学者很难掌握这些定义。有人能给我一个外行人的理解(最好是说明性的例子)我如何解决我的问题?

2 个答案:

答案 0 :(得分:2)

Django中包含user_passes_test装饰器。您不必自己制作装饰。

from django.contrib.auth.decorators import user_passes_test

def check_special_user(user):
    return user.filter(is_special=True)

# if not the special user it will redirect to another login url , otherwise process the view
@user_passes_test(check_special_user,login_url='/login/') 
def my_view(request):
   pass
    ...

需要装饰器中的请求

为此,请在您的项目或应用中制作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):  # change this line to request instead of 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
  

将test_func(request.user)更改为test_func(request),您将获得   装饰函数中的整个请求。

修改:在url.py中,

url (
    r'^your-url$',
    user_passes_test(check_special_user, login_url='/login/')(
        my_view
    ),
    name='my_view'
)

答案 1 :(得分:1)

这是理解python装饰器的最佳答案:How to make a chain of function decorators?

您可以使用login_requiredlogin_url参数:

@login_required(login_url='some_url)

另一种方法是创建自定义装饰器,例如documentation of Django

from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return user.email.endswith('@example.com')

@user_passes_test(email_check)
def my_view(request):
    ...