Django HttpResponseRedirect无法在自定义权限(authentication.py)中工作

时间:2016-03-10 13:10:29

标签: python django permissions django-rest-framework

我创建了一个自定义权限,用于检查用户是否已登录。我通过令牌检查它,如果令牌不存在,则不会登录,因此应将其重定向到主页。我已经导入了所有必要的要求,如HttpResponseRedirect和其他东西。这在我的视图集中用作permission_class(在某些方法中,我将响应呈现为html模板,并将其呈现为json)。这是代码:

class AccountPermission(permissions.BasePermission):
    message = "Not a valid customer"

    def has_permission(self, request, view):
        if not token:
            return HttpResponseRedirect('/')
        else:
            return True

问题是Viewset将自定义权限中的HttpResponseRedirect html视为True,并允许用户使用Viewset中的方法。如何避免这种情况?

1 个答案:

答案 0 :(得分:1)

嘿,我找到了解决方案。如果将来有人需要,这会很有帮助。我为休息框架异常创建了一个异常处理程序,并在settings.py文件中启动:

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'app_name.exception.function_name'
}

我在exception.py中创建了异常处理函数custom_exception_handler:

from rest_framework.views import exception_handler
from django.http import HttpResponseRedirect

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None and response.status_code == 403:
        return HttpResponseRedirect("/")
else:
    return response