当前位置:  开发笔记 > 后端 > 正文

DRF自定义权限

如何解决《DRF自定义权限》经验,为你挑选了0个好方法。

我正在尝试在Django rest框架中建立自定义权限-

class GroupBasePermission(permissions.BasePermission):

    group_name = ""

    def has_permission(self, request, view):
        """
        Should simply return, or raise a 403 response.
        """
        print 'self.group_name == ', self.group_name
        try:
            request.user.groups.get(name=self.group_name)    
        except Group.DoesNotExist:
            print 'group does not exist'
            msg = ('Permission denied.')
            data = {'detail': six.text_type(msg)}
            #return Response(data, status=status.HTTP_403_FORBIDDEN)
            return HttpResponseForbidden()

class HRAdminGroupPermission(GroupBasePermission):
    """
        Checks to see if a user is in a particular group
    """

    group_name = "HR Admin1"

这是我的看法

class CompanyCreateApiView(LoginRequiredMixin,OTPRequiredMixin,GroupRequiredMixin,CreateAPIView):

    permission_classes = (IsAuthenticated, HRAdminGroupPermission,)
    authentication_classes = (SessionAuthentication,)
    group_required = 'HR Admin1'


    def post(self, request, *args, **kwargs):
        for each in self.request.user.groups.all():
            print 'self.request.user.group == ', each.name

当我使用用户(GROUP-- HR ADMIN)调用此API时,即使我在权限异常中看到了打印msg,也不会引发403禁止错误。

如何解决此问题?

推荐阅读
地之南_816
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有