使用DRF内置的权限类

未经身份验证的用户,拒绝访问

  1. permissions.IsAuthenticated

未经身份验证的用户,只读

  1. permissions.IsAuthenticatedOrReadOnly
  1. from rest_framework import generics, permissions
  2. class DomainList(generics.ListCreateAPIView):
  3. queryset = Domain.objects.all()
  4. serializer_class = DomainSerializer
  5. filter_class = DomainFilter
  6. permission_classes = [permissions.IsAuthenticated, ]

自定义权限类

  1. from rest_framework import permissions
  2. class IsOwnerOrReadOnly(permissions.BasePermission):
  3. """
  4. 自定义权限只允许对象的所有者编辑它。
  5. """
  6. def has_object_permission(self, request, view, obj):
  7. # 读取权限允许任何请求,
  8. # 所以我们总是允许GET,HEAD或OPTIONS请求。
  9. if request.method in permissions.SAFE_METHODS:
  10. return True
  11. # 只有该snippet的所有者才允许写权限。
  12. return obj.owner == request.user
  1. from rest_framework import generics, permissions
  2. from .permissions import IsOwnerOrReadOnly
  3. class DomainList(generics.ListCreateAPIView):
  4. queryset = Domain.objects.all()
  5. serializer_class = DomainSerializer
  6. filter_class = DomainFilter
  7. permission_classes = [permissions.IsAuthenticated,
  8. IsOwnerOrReadOnly]

相关文档

https://q1mi.github.io/Django-REST-framework-documentation/api-guide/permissions_zh/