1

Restframework 权限permission 组件实例-2

 

1.在视图类里添加权限组件

class BookView(APIView):
    authentication_classes = [UserAuth]
    permission_classes = [SVIPPermission]

    def get(self,request):
        """
        查看所有书籍
        :param request:
        :return:
        """
        book_list=Book.objects.all()
        serializer= BookSerializer(book_list,many=True)
        return Response(serializer.data)

    def post(self,request):
        """
        添加一条书籍
        :param request:
        :return:
        """
        serializer=BookSerializer(data=request.data,many=True)
        if serializer.is_valid():
            serializer.save()#create操作.
            return Response(serializer.data)
        else:
            return Response(serializer.errors)

 

2.设置权限类

from rest_framework.permissions import AllowAny

class SVIPPermission(object):
    message="您没有权限访问该资源"
    def has_permission(self,request,view):
        if request.user.user_type>=1:
            return True
        return False

 

3. 设置全局类权限

REST_FRAMEWORK={

'DEFAULT_AUTHENTICATION_CLASSES': (
  'app01.utils.auth_class.UserAuth',
),
    'DEFAULT_PERMISSION_CLASSES': (
        'app01.utils.svippermission.SVIPPermission',
    ),

}

 

4.查看效果

 

 

posted @ 2018-09-20 20:54  萌哥-爱学习  阅读(274)  评论(0编辑  收藏  举报