在装饰器内调用login_required

时间:2018-03-23 09:54:47

标签: python django decorator

我试图编写一个自定义装饰器,它将进行一些检查以查看用户是否有权访问页面,但在此之前,需要对用户进行身份验证。我想过使用Django的login_required装饰器,然后做我的自定义逻辑,但我似乎找不到任何方法来调用我自己的login_required装饰器。

我知道有其他选择,比如装饰我的观点:

@login_required
@my_custom_decorator
def my_view(request):
    pass

或检查我的装饰者内的user.is_authenticated()

def my_custom_decorator(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated():
            redirect(...)

但是,我想从login_required使用Django的逻辑。

有没有办法在装饰器中调用装饰器,或者在不使用2个独立装饰器的情况下以任何其他方式实现我的逻辑?

1 个答案:

答案 0 :(得分:1)

你的装饰者会返回一个函数,例如

def my_custom_decorator(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        ...
    return wrapper

您可以在返回之前将该功能包装在login_required中:

def my_custom_decorator(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        ...
    return login_required(wrapper)