DRF ViewSet操作授权与规则



考虑以下型号

class MyUser(AbstractBaseUser):
ADMIN = 0
TEACHER = 100
STUDENT = 200
UNSPECIFIED = 256
USER_TYPE_CHOICES = (
(ADMIN, 'admin'),
(TEACHER, 'teacher'),
(STUDENT, 'student'),
(UNSPECIFIED, 'unspecified')
)
...
user_type = models.IntegerField(db_column='userType', choices=USER_TYPE_CHOICES, blank=True, default=UNSPECIFIED)

下面的ViewSet

class CourseViewSet(ViewSet):
def create(self, request):
serializer = CourseSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)

使用django规则,如何将CourseViewSet中的create((操作仅限于user_type TEACHER的用户?

如果您想自动应用模型中定义的权限,可以使用

在你的课程模型中,像这样的

from rules import predicates
@predicates.predicate()
def check_teacher(user):
if not hasattr(user, 'user_type'):
return False
if user.user_type == 'teacher':
return True
return False

class Course(models.Model):
....
class Meta:
rules_permissions = {
"add": check_teacher,
"read": rules.always_allow,
}

和您的视图

from rules.contrib.rest_framework import AutoPermissionViewSetMixin
class CourseViewSet(AutoPermissionViewSetMixin, viewsets.ViewSet):
def get_queryset(self):
return Course.objects.all()
def create(self, request):
serializer = CourseSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)

相关内容

  • 没有找到相关文章

最新更新