【问题标题】:Differentiating unauthenticated users in custom decorator在自定义装饰器中区分未经身份验证的用户
【发布时间】:2017-07-26 11:42:24
【问题描述】:

这里是 Django 初学者。

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

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

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

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    【讨论】:

    • 问题:如何获得check_special_user 中的推荐网址?我那里没有request
    • 没有请求不能在 user_passes_test 方法装饰器中使用。你到底想做什么?
    • 就像我在问题中提到的那样,我正在尝试向来自我应用程序中某些 URL 的 unauth 用户 显示一个特殊的登录页面(例如 /buy_and_sell/)。所有其他 unauth 用户将显示一个通用登录页面。为此,我需要查看request.META.get('HTTP_REFERER') 的内容。
    • '试图向来自某些 url 的用户显示一个特殊的登录页面' - 您是否为此在用户表中进行了任何更改?就像用户现在起源一样。
    • 不,用户在此流程中未经身份验证,我在用户表中没有更改任何内容。只想向这组特殊的 unauth 用户显示特殊的登录页面,并向所有其他 unauth 用户显示通用登录页面。
    【解决方案2】:

    这里是理解 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):
        ...
    

    【讨论】:

    • 无论如何我都会为您的回答 +1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多