使用DRF内置的权限类
未经身份验证的用户,拒绝访问
permissions.IsAuthenticated
未经身份验证的用户,只读
permissions.IsAuthenticatedOrReadOnly
from rest_framework import generics, permissions
class DomainList(generics.ListCreateAPIView):
queryset = Domain.objects.all()
serializer_class = DomainSerializer
filter_class = DomainFilter
permission_classes = [permissions.IsAuthenticated, ]
自定义权限类
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
自定义权限只允许对象的所有者编辑它。
"""
def has_object_permission(self, request, view, obj):
# 读取权限允许任何请求,
# 所以我们总是允许GET,HEAD或OPTIONS请求。
if request.method in permissions.SAFE_METHODS:
return True
# 只有该snippet的所有者才允许写权限。
return obj.owner == request.user
from rest_framework import generics, permissions
from .permissions import IsOwnerOrReadOnly
class DomainList(generics.ListCreateAPIView):
queryset = Domain.objects.all()
serializer_class = DomainSerializer
filter_class = DomainFilter
permission_classes = [permissions.IsAuthenticated,
IsOwnerOrReadOnly]
相关文档
https://q1mi.github.io/Django-REST-framework-documentation/api-guide/permissions_zh/