Permission_classes不起作用。问题在哪里?

时间:2019-05-28 06:09:38

标签: permissions django-rest-framework

我试图找到Restframework的权限如何工作,所以我尝试编写一些代码来响应一个简单的Json。但是,是否存在‍ permission_classes不会影响代码的执行,并且端点将在不检查任何许可的情况下响应所有请求。

这是我的代码:

class TeacherStatisticPost(generics.RetrieveAPIView):
    permission_classes = (ClassOwnerPermission)
    queryset = ClassRoom.objects.all()
    lookup_field = "id"
    lookup_url_kwarg = 'classRoom_id'

    def get_klass(self):
        class_id = self.kwargs['classRoom_id']
        return ClassRoom.objects.get(id=classRoom_id)

    def get(self, request, *arg, **kwargs):
        klass = self.get_klass()
        response ={
             'class_room_grade' : klass.grade,
              'class_room_name' : klass.name,
             }
        return JsonResponse(response, safe=False)

这是我的权限。py:

class ClassOwnerPermission(permissions.BasePermission):

    def has_perm(self, user, klass):
        print("now in class perm") # never print out any thing!
        return klass.owner == user

    def has_object_permission(self, request, view, obj): # where is come from 'obj' ?
        return self.has_perm(request.user, obj)

我尝试设置权限,仅ClassRoom的所有者可以访问此端点。

1 个答案:

答案 0 :(得分:2)

首先,DRF希望 Widget PlayerOptionContainer(){ return Column( children: <Widget>[ Expanded(flex:25, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded(flex: 30,child: _logoContainer(width),), Expanded(flex: 70,child: searchContainer(),), ],),), Expanded(flex:75,child: Container( decoration: BoxDecoration(color: Colors.transparent), child: GridView.count( crossAxisCount: 3, children: List.generate(20, (index) { return Container( margin: EdgeInsets.only(left: width*0.02, bottom: width*0.02, right: width*0.02), decoration: BoxDecoration( color: MyColors.yellowBg, borderRadius: new BorderRadius.circular(12.0), ), child: Center(child: MyFeedTile(),), ); }), ), ),)], ); } 是列表或元组。 permission_classes行中的permission_classes既不是元组也不列出。在permission_classes = (ClassOwnerPermission)后面加上逗号。

ClassOwnerPermission行应该起作用。

第二,您不使用permission_classes = (ClassOwnerPermission, )方法来检查权限。删除get_object方法并使用get_object

您的视图应如下所示:

def get_klass(self):