简体   繁体   中英

How to write permissions in a viewset with conditional statements in DRF?

I have a viewset written in DRF:

class MyViewSet(ModelViewSet):
    serializer_class = MySerializer
    queryset = models.MyClass.objects.all()

    def get_serializer_class(self):
        permission = self.request.user.permission
        if permission=='owner' or permission=='admin': 
            return self.serializer_class
        else:
            return OtherSerializer

    def perform_create(self, serializer):
        permission = self.request.user.permission
        if permission=='owner' or permission=='admin': 
            serializer.save() 

        else:
            employee = models.Employee.objects.get(user=self.request.user)
            serializer.save(employee=employee)

Here, I am using the following statements in both get_serializer_class and perform_create which looks like a repetitive code:

permission = self.request.user.permission
        if permission=='owner' or permission=='admin': 

Is there any way to write it once and then use it as a permission_class somehow?

Create a Custom Permission class https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

from rest_framework.permissions import BasePermission, SAFE_METHODS
    class CustomPermission(BasePermission):
        def has_permission(self, request, view):
            if request.method in SAFE_METHODS:
                return True
            permission = self.request.user.permission
            if permission=='owner' or permission=='admin': 
                return True
            return False 

in Views.py

class MyViewSet(ModelViewSet):
    serializer_class = MySerializer
    queryset = models.MyClass.objects.all()
    permission_classes = (CustomPermission,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM